The implementation of Android MVP based on an example

Source: Internet
Author: User

Recently read the project's source code, found that there are MVP traces of the project, but they do not have a good understanding of the relevant code implementation logic. The main reason is that their understanding of the MVP is too conceptual, has not really been manipulated. This article intends to analyze a simple example of a MVP to help him better understand the internal idea of MVP.

For what is the difference between MVP,MVP and MVC, MVP is a bit, you can refer to this article: MVP mode Simple and understandable introduction. The article also has the demo, can help everybody to understand better.

Today's analysis is a person to write the demo, in fact, the author also wrote an article to introduce (Android MVP with Fragment and Recyclerview), then why do I have to analyze it? In fact, I have modeled this demo to use MVP's ideas on a demo of their own. However, the time has long, and forgot, so I intend to comb under. Of course, the article will certainly not be the same as the author's article, have to put forward their own ideas. The demo is also optimized to make it more consistent with the MVP idea.

It is recommended to read the first two articles, and then look at this article, so that you can better understand the content of the article.

A brief analysis of code structure

First, let's look at the structure of the code. You can see that there are 6 folders, which are related to MVP mode in the following three folders. The model contains classes that are related to data. Picture is the data model, and several other classes are responsible for downloading the picture to get the data. The model and view references are introduced in Presenter to control the model and view. There is only one Pictureview class in view, but strictly speaking, picturefragment and Pictureadapter should also be placed in the folder view, but this is also possible.

Implementing a logical Overall overview

The thing to do in this project is simply to download the image from the Web, display it on the phone, click on the picture, and pop up a Toast.

Thinking analysis

Mvp? Here M is not a picture, so there will definitely be an entity class. The picture needs to be downloaded, so a class is also created to control it, but the final call is downloaded in P.

The V? It is Fragment, composed of Recyclerview and ProgressBar. Pictureview is an interface for controlling the display of pictures and so on. However, it is also called in P.

The last is P, which encapsulates the operation of M, V, the class Picturepresenterimpl.

Code implementation

M implementation (only the important code is affixed):

 Public classPictureinteractorimplImplementsPictureinteractor {Private Final Staticstring[] Picturenames = {            "Rocket in the Universe",            "A scene in London",            "Moon over Mountains",            "A Simple Moon",            "Sun and Volcano",            "A Collection of Mountains",            "River between Mountains",            "Some Pine Trees",            "On Small Town",            "Volcanos Reflection"    }; Private Final Static intPictureimages[] ={R.drawable.cohete_flat, R.drawable.london_flat, R.drawable.material_flat, R.drawable.moon_flat, R.drawable.mountain_flat, R.drawable.mountain_mo_flat, r.drawabl    E.moutain_go_flat, R.drawable.pine_flat, R.drawable.towers_flat, R.drawable.vulcan_flat    }; @Override Public voidLoadpictures (FinalLoaderlistener Listener) {        NewHandler (Looper.getmainlooper ()). postdelayed (NewRunnable () {@Override Public voidrun () {listener.onfinish (Createpictures ()); }                }, 2000); }    PrivateList<picture>createpictures () {ArrayList<Picture> pictures =NewArraylist<>();  for(inti = 0; i < picturenames.length; i++) {Pictures.add (NewPicture (Picturenames[i], pictureimages[i])); }        returnPictures; }}

Everyone look at the above code, only Loadpictures is from the interface, why Createpictures method is not written in the interface? The main reason is that the method written on the interface is to be called in P. If external calls are not required, there is no need for the interface.

V implementation (only the important code is affixed):

 Public Interface Pictureview {    void  showprogressbar ();     void Hideprogressbar ();     void showmsg (String msg);     void showpictures (list<picture> pictures);}

Although only pictureview a class in view, from this class you can be clear about what the view is going to do.

Implementation of P (only the important code is affixed):

 Public classPicturepresenterimplImplementsPicturepresenter, Loaderlistener {PrivatePictureview Mpictureview; PrivatePictureinteractor Minteractor;  PublicPicturepresenterimpl (Pictureview pictureview) { This. Mpictureview =Pictureview; Minteractor=NewPictureinteractorimpl (); } @Override Public voidOnresume () {Mpictureview.showprogressbar (); Minteractor.loadpictures ( This); } @Override Public voidOnDestroy () {Mpictureview=NULL; } @Override Public voidOnitemclick (intPOS)    {Mpictureview.showmsg (string.valueof (POS)); } @Override Public voidOnFinish (list<picture>pictures)        {Mpictureview.hideprogressbar ();    Mpictureview.showpictures (Pictures); }}

As can be seen, P is in fact the logic of the M,V is encapsulated, unified by its control.

Finally speaking fragment, the internal introduction of P. The main reason is that P cannot control the life cycle, so it is necessary to borrow the life cycle of fragment to control the whole process.

Questions?

Everyone looked at the above demo, do not feel in the fragment, that is, mixed with V, and P, this is actually not conducive to maintenance, especially when the view more and more time, then, also to the view of the initialization and so on are written in the fragment? So the next part of the fragment content to thin body. How do you lose weight? Please see below for details.

Reform

After the reconstructed structure, only a new Basepageview is created in view to handle the initialization and control logic of the view.

The code is specific as follows:

 Public classBasepageviewextendsFramelayoutImplementsPictureview {PrivateRecyclerview Mrecyclerview; PrivateProgressBar mprogress; PrivatePictureadapter Madapter; PrivatePicturepresenter Mpresenter; PrivateContext Mcontext; /*** constructor function. */     PublicBasepageview (Context context) { This(Context,NULL);    };  PublicBasepageview (Context context, AttributeSet AttributeSet) { This(context, AttributeSet, 0); }     PublicBasepageview (context context, AttributeSet AttributeSet,intdefstyleattr) {        Super(context, AttributeSet, defstyleattr);    Init (context); }    /*** Initialize*/     Public voidinit (Context context) {Mcontext=context; Inflate (Mcontext, R.layout.base_view_layout, This); Mrecyclerview=(Recyclerview) Findviewbyid (R.id.recycler_view); Mprogress=(ProgressBar) Findviewbyid (R.id.progress_bar); Mrecyclerview.setlayoutmanager (NewLinearlayoutmanager (Mcontext)); } @Override Public voidShowprogressbar () {mprogress.setvisibility (view.visible);    Mrecyclerview.setvisibility (view.invisible); } @Override Public voidHideprogressbar () {mprogress.setvisibility (view.invisible);    Mrecyclerview.setvisibility (view.visible); } @Override Public voidshowmsg (String msg) {Toast.maketext (Mcontext, MSG, Toast.length_long). Show (); } @Override Public voidShowpictures (list<picture>pictures) {Madapter=Newpictureadapter (Pictures); Madapter.setrecycleritemclicklistener (NewOnrecycleritemclicklistener () {@Override Public voidOnitemclick (intPOS)            {Mpresenter.onitemclick (POS);        }        });    Mrecyclerview.setadapter (Madapter); }}

This way, when you need to make changes to the view, you just need to change the class so that you don't have to run into fragment.

At the same time, fragment also slimming success:

 Public classPicturefragmentextendsfragment{PrivatePicturepresenter Mpresenter;  Public Staticpicturefragment newinstance () {return Newpicturefragment (); }     Publicpicturefragment () {} @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); } @Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate ) {View View= Inflater.inflate (R.layout.fragment_picture, container,false); Basepageview Basepageview=(Basepageview) View.findviewbyid (R.id.baseview); Mpresenter=NewPicturepresenterimpl (Basepageview); returnview; } @Override Public voidOnresume () {Super. Onresume ();    Mpresenter.onresume (); } @Override Public voidOnDestroy () {Super. OnDestroy ();    Mpresenter.ondestroy (); }}

After the transformation, is not a better understanding AH. When we need to modify a certain part of the time, we can easily locate the place to modify.

Well, after the transformation, I believe that everyone's understanding of the MVP is even more profound.

I hope this article will be of some help to you.

The implementation of Android MVP based on an example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.