Android--A tentative approach to MVP mode

Source: Internet
Author: User

1, I believe you are very familiar with the MVP model, m-model-model, v-view-view, c-controller-Controller. The MVP evolved as an MVC version, similar to the meaning of MVC: The m-model-model, the v-view-view, the p-presenter-representation. From the combination of MVC and MVP, Controlller/presenter plays the role of logical control in MVC/MVP, and plays a role in controlling the business processes. The most different aspect of MVP and MVC is that M is not directly related to V, and that there is no direct relationship between model and view, between which the presenter layer is responsible for regulating the indirect interaction between view and model. One of the important things about Android is that the UI operation basically needs to be done asynchronously, that is, to manipulate the UI in Mainthread, so it is reasonable to separate the view from the model. In addition, the interaction of presenter with view and model can further achieve loose coupling by using interface definition interaction and can be more convenient for unit testing through interfaces. Here are the corresponding two graphs (MVC on the left and MVP on the right):

The most obvious difference is that MVC allows model and view interaction, while the interaction of model and view in MVP is done by presenter, and presenter and view interactions are implemented through interfaces.

2,MVP implementation of the application (example is the great God blog written, I just came to write about the realization of the idea, after all, the level of small rookie)

First look at the effect you want to achieve:

Take a look at our catalog of projects:

This is one of the most common sign-in functions, as we can see from the above features, so first we will create a user class that contains the username and password for the user information entered by the user.

①model Layer

User.java

Package com.wangjitao.simplelogindemo.bean;/** * Created by Wangjitao on 2016/5/12. * User Login Bean */public class User {    private String username;    private String password;    Public String GetUserName () {        return username;    }    public void Setusername (String username) {        this.username = username;    }    Public String GetPassword () {        return password;    }    public void SetPassword (String password) {        this.password = password;    }}

From the functions given above, we can see that we are mainly to implement the login function, so there is at least one login () method

Iuserbiz.java

Package Com.wangjitao.simplelogindemo.inter;import com.wangjitao.simplelogindemo.listener.onloginlistener;/** * Created by Wangjitao on 2016/5/12. */public interface Iuserbiz {public    void Login (string username, string password, Onloginlistener loginlistener);}

Its implementation class Userbiz.java, in the implementation class we simulate a login time-consuming operation, and then in the login successfully wrote a callback class Onloginlistener.java

Userbiz.java

Package Com.wangjitao.simplelogindemo.inter;import Com.wangjitao.simplelogindemo.bean.user;import com.wangjitao.simplelogindemo.listener.onloginlistener;/** * Created by JH on 2016/5/12. */public class Userbiz implements iuserbiz{@Override public void Login (final string username, final string password , final Onloginlistener Loginlistener) {//Turn on child threads to simulate login time-consuming Operation New Thread () {@Override publi                c void Run () {try {thread.sleep (2000);                } catch (Interruptedexception e) {e.printstacktrace ();                    }//Simulate Login Success if ("Wjt". Equals (username) && "123456". Equals (password)) {                    User user = new user ();                    User.setusername (username);                    User.setpassword (password);                loginlistener.loginsuccess (user);                }else {loginlistener.loginfailed ();      }      }}.start (); }}

Onloginlistener.java

Package Com.wangjitao.simplelogindemo.listener;import com.wangjitao.simplelogindemo.bean.user;/** * Created by Wangjitao on 2016/5/12. */public interface Onloginlistener {    void loginsuccess (user user);    void loginfailed ();}

②view Layer

From the interface we see we can see that the user has a total of two buttons, one is login, then need two ways to get the user name and password

String GetUserName (); String GetPassword ();

  

Then there's a clear button, and we're going to provide two ways to clear the contents of the input box.

void Clearusername (); void Clearpassword ();

Then when the user is logged in, we need a user's wait, we need to add a progress cue bar

void Clearusername (); void Clearpassword ();

Then is the user login after some hints, when the login successful, let the user jump to the next interface, when the login failed prompt user name or password error

void tomainactivity (user user); void Showfailederror ();

So the view interface is as follows:

Package Com.wangjitao.simplelogindemo.view;import com.wangjitao.simplelogindemo.bean.user;/** * Created by JH on 2016/ 5/12. */public interface Iuserloginview {    String getusername ();    String GetPassword ();    void Showloading ();    void Dismissloading ();    void tomainactivity (user user);    void Showfailederror ();    void Clearusername ();    void Clearpassword ();}

Then the activity to implement this interface method (activity can also be used as a view layer)

Package Com.wangjitao.simplelogindemo;import Android.support.v7.app.appcompatactivity;import Android.os.Bundle; Import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.progressbar;import Android.widget.toast;import Com.wangjitao.simplelogindemo.bean.user;import Com.wangjitao.simplelogindemo.presenter.userloginpresenter;import Com.wangjitao.simplelogindemo.view.iuserloginview;public class Mainactivity extends Appcompatactivity implements    iuserloginview{private EditText edittext_username, Edittext_password;    Private Button Button_login, Button_clean;    Private ProgressBar ProgressBar;    Private Userloginpresenter Muserloginpresenter = new Userloginpresenter (this);        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); } private void Initview () {edittext_username = (editText) Findviewbyid (r.id.eDittext_username);        Edittext_password = (editText) Findviewbyid (R.id.edittext_password);        Button_login = (Button) Findviewbyid (R.id.button_login);        Button_clean = (Button) Findviewbyid (R.id.button_clean);        ProgressBar = (ProgressBar) Findviewbyid (R.id.progressbar);                 Button_login.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Muserloginpresenter.login ();        }        });                 Button_clean.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Muserloginpresenter.clear ();    }        });    } @Override Public String GetUserName () {return Edittext_username.gettext (). toString ();    } @Override Public String GetPassword () {return Edittext_password.gettext (). toString ();    } @Override public void showloading () {progressbar.setvisibility (view.visible); } @OveRride public void dismissloading () {progressbar.setvisibility (view.gone); } @Override public void tomainactivity (user user) {Toast.maketext (mainactivity.this, "Login successful: Welcome back" +user.getuse    Rname (), Toast.length_short). Show (); } @Override public void Showfailederror () {Toast.maketext (mainactivity.this, "Login Failed", Toast.length_short). Show    ();    } @Override public void Clearusername () {Edittext_username.settext ("");    } @Override public void Clearpassword () {Edittext_password.settext (""); }}

③persenter

This interaction with the data and view, our application is mainly login and clear, so the code is as follows:

Package Com.wangjitao.simplelogindemo.presenter;import Android.os.handler;import Com.wangjitao.simplelogindemo.bean.user;import Com.wangjitao.simplelogindemo.inter.iuserbiz;import Com.wangjitao.simplelogindemo.inter.userbiz;import Com.wangjitao.simplelogindemo.listener.OnLoginListener; Import com.wangjitao.simplelogindemo.view.iuserloginview;/** * Created by Wangjitao on 2016/5/12.    */public class Userloginpresenter {private iuserbiz userbiz;    Private Iuserloginview Userloginview;    Private Handler Mhandler = new Handler ();        Public Userloginpresenter (Iuserloginview userloginview) {this.userloginview = Userloginview;    userbiz = new Userbiz ();        } public void Login () {userloginview.showloading ();            Userbiz.login (Userloginview.getusername (), Userloginview.getpassword (), new Onloginlistener () {@Override            public void loginsuccess (final User user) {mhandler.post (new Runnable () {@Override        public void Run () {userloginview.tomainactivity (user);                   Userloginview.dismissloading ();            }               });                   } @Override public void loginfailed () {Mhandler.post (new Runnable () {                       @Override public void Run () {userloginview.showfailederror ();                   Userloginview.dismissloading ();            }               });    }        });        } public void Clear () {userloginview.clearusername ();    Userloginview.clearpassword (); }}

Presenter is basically getting the required parameters from the view, giving the model a way to execute the business method, the feedback needed during the execution, and the results, and then the view to do the corresponding display.

So we finished the demo, feeling still very fulfilling.

 

  

  

  

  

  

  

Android--A tentative approach to MVP mode

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.