Talking about MVP in Android

Source: Internet
Author: User

I. Overview

For MVP (Model View Presenter), most people can say one or two: "Evolutionary version of MVC", "Make Model and View fully decoupled" and so on. This blog post is just for the record, to make some comments, and to help you write code for the MVP style for an activity page.

For MVP, there is a problem in my heart:

Why should this model be accepted by the vast majority of Android programmers?

Asked some programmers, their general understanding of MVP is: "The code is clear, but there are many classes added." The first time I saw the MVP, I saw a demo, after reading it feels very nice (but back, I think of an example to write, the headache can not be written out, of course, this will be said later in the article). The reason for Nice is because it does make the clarity of the code a great boost.

So, Ascension is generally compared, and in retrospect, there is no code structure to apply MVP. Many people say it's obviously MVC:

    • View: Corresponds to a layout file
    • Model: Business logic and entity model
    • Controllor: Corresponds to activity

It does look like that, but think about it. The view corresponds to the layout file, in fact, there are very few things to do, in fact, about the data binding in the layout file operation, the event handling code is in the activity, It causes the activity to be both a view and a controller (Data-binder, of course, might make the view look more like a view). This may be why, in this article, there is one sentence:

Most of the modern Android applications just use View-model architecture,everything are connected with Activity.

When the schema is changed to MVP, presenter's appearance, actvity as the view layer, presenter is responsible for the completion of the view layer and the model layer of interaction. Now this is the case:

    • View corresponds to activity, which is responsible for drawing the view and interacting with the user
    • Model is still business logic and entity model
    • Presenter is responsible for the interaction between view and model

OK, the first simple to understand, the text will have an example of the time can be intuitive to feel under.

Small summary, that is, the reason is refreshing, because the jump is from 并不标准的MVC MVP a change, reducing the activity of the responsibility, simplifying the activity of the code, the complex logic code extracted into the presenter for processing. The corresponding benefit is that the coupling degree is lower and more convenient to test. To borrow two pictures (from: This article), representing the above transformations:

Change to:

Second, the difference between MVP and MVC

OK, it says a bunch of theories, and here's a look at the difference between MVC and MVP, see (from: This article):

In fact, the most obvious difference is that MVC allows model and view to interact, and the MVP is clearly the interaction between model and view is done by presenter. Another point is that the interaction between the presenter and the view is through the interface (which is reflected in the code).

There are a bunch of conceptual things, as well as the advantages of a little, interested in self-Baidu. Here are some simple requirements to show how to write the MVP demo.

Third, simple Login Demo

To see this effect, first look at the project structure after completion:

OK, let's start with a step-by-step approach to writing.

(a) Model

First the entity class user does not have to consider this certainly has, second from can see at least one business method login (), these two points is not difficult, we first complete:

Package Com.zhy.blogcodes.mvp.bean;/** * Created by Zhy on 15/6/18. */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;}}        

package;/** * Created by zhy on 15/6/19. */public interface IUserBiz{ public void login(String username, String password, OnLoginListener loginListener);}

Package;Import Com.zhy.blogcodes.mvp.bean.User;/** * Created by Zhy on 15/6/19. */PublicClassUserbizImplementsiuserbiz{@OverridePublicvoidLoginFinal String username,Final String Password,final onloginlistener Loginlistener) {//simulate child threads time consuming operation new thread () {@ Override public void run () {try {thread.sleep (2000);} catch (interruptedexception e) {e.printstacktrace ();} //simulation login succeeded if ( "Zhy". Equals ( username) &&  "123". Equals (password)) {User user = new User (); User.setusername (username); User.setpassword (password); loginlistener.loginsuccess (user); } else {loginlistener.loginfailed ();}}}. Start (); }}
package;import com.zhy.blogcodes.mvp.bean.User;/** * Created by zhy on 15/6/19. */public interface OnLoginListener{ void loginSuccess(User user); void loginFailed();}

Entity class Needless to say, as for the business class, we have extracted an interface, an implementation class which is also very common ~~login method, is usually connected to the server, is a time-consuming operation, so we opened up a sub-thread, Thread.Sleep (2000) simulated time-consuming, because it is time-consuming operation, So we use a callback interface to notify the state of the login.

In fact, this is still relatively good writing, because it is not different from the traditional wording.

(ii) View

As we said above, presenter and view interactions are through interfaces. So here we need to define one ILoginView , the difficulty lies in what should be the method, we take a look at:

Can see we have two buttons, one is login, the other is clear;

Login indicates that you want to have a user name, password, then the corresponding two methods:

    String getUserName();    String getPassword();

Moreover login is a time-consuming operation, we need to give the user a friendly hint, generally is Operation ProgressBar, so again two:

    void showLoading();    void hideLoading()

Login Of course there is login success and failure processing, we mainly see success we are jump activity, and failure may be to give a reminder:

    void toMainActivity(User user);    void showFailedError();

Ok,login This method we have finished analysis ~ ~ There is a clear that is simple:

    void clearUserName();    void clearPassword()

Fully integrated, the interface is:

package com.zhy.blogcodes.mvp.view;import com.zhy.blogcodes.mvp.bean.User;/** * Created by zhy on 15/6/19. */public interface IUserLoginView{ String getUserName(); String getPassword(); void clearUserName(); void clearPassword(); void showLoading(); void hideLoading(); void toMainActivity(User user); void showFailedError();}

With the interface, the implementation is too good to write ~ ~ ~

In summary, for the view interface, to observe the function of the operation, and then consider:

    • What does the operation require? (GetUserName, GetPassword)
    • The results of the operation, corresponding feedback? (Tomainactivity, Showfailederror)
    • The corresponding friendly interaction during the operation? (Showloading, hideloading)

The following is the implementation of our view of the class, ha, in fact, is activity, the article began to say that the MVP of the view is actually activity.

Package COM.ZHY.BLOGCODES.MVP;Import Android.os.Bundle;Import;Import Android.view.View;Import Android.widget.Button;Import Android.widget.EditText;Import Android.widget.ProgressBar;Import Android.widget.Toast;Import COM.ZHY.BLOGCODES.R;Import Com.zhy.blogcodes.mvp.bean.User;Import Com.zhy.blogcodes.mvp.presenter.UserLoginPresenter;Import Com.zhy.blogcodes.mvp.view.IUserLoginView;PublicClassUserloginactivityExtendsActionbaractivityImplementsiuserloginview{Private EditText metusername, Metpassword;Private Button Mbtnlogin, mbtnclear;Private ProgressBar mpbloading;Private Userloginpresenter Muserloginpresenter =New Userloginpresenter (this);@OverrideProtectedvoidOnCreate (Bundle savedinstancestate) {Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_user_login); Initviews (); }PrivatevoidInitviews () {metusername = (EditText) Findviewbyid (; Metpassword = (EditText) Findviewbyid ( _et_password); Mbtnclear = (Button) Findviewbyid (; Mbtnlogin = (Button) Findviewbyid (; mpbloading = (ProgressBar) Findviewbyid (; Mbtnlogin.setonclicklistener (New View.onclicklistener () {@OverridePublicvoidOnClick (View v) {muserloginpresenter.login ();}}); Mbtnclear.setonclicklistener (New View.onclicklistener () {@OverridePublicvoidOnClick (View v) {muserloginpresenter.clear ();}}); }@OverridePublic StringGetUserName () {Return Metusername.gettext (). toString (); }@OverridePublic StringGetPassword () {Return Metpassword.gettext (). toString (); }@OverridePublicvoidClearusername () {Metusername.settext (""); }@OverridePublicvoidClearpassword () {Metpassword.settext (""); }@OverridePublicvoidshowloading () {mpbloading.setvisibility (view.visible);}  @Override public void hideloading () {mpbloading.setvisibility (view.gone);}  @Override public void tomainactivity (user user) {toast.maketext (this, User.getusername () +  "login success, to Mainactivity", Toast.length_short). Show (); }  @Override public void showfailederror () {Toast.maketext (this,  

It is an easy task to implement the interface we defined above in activity, after all, the interface guides us to complete it.

Finally, look at our presenter.

(c) Presenter

Presenter is used as a bridge between model and view, what should be the method?

In fact, it is also mainly to see what the operation of the function, such as this example, two operations: Login and clear.

Package com.zhy.blogcodes.mvp.presenter;Import Android.os.Handler;Import Com.zhy.blogcodes.mvp.bean.User;Import;Import;Import;Import Com.zhy.blogcodes.mvp.view.IUserLoginView;/** * Created by Zhy on 15/6/19. */PublicClassuserloginpresenter{Private Iuserbiz userbiz;Private Iuserloginview Userloginview;Private Handler Mhandler =New Handler ();PublicUserloginpresenter (Iuserloginview userloginview) {This.userloginview = Userloginview;This.userbiz =New Userbiz (); }PublicvoidLogin () {userloginview.showloading (); Userbiz.login (Userloginview.getusername (), Userloginview.getpassword (),New Onloginlistener () {@OverridePublicvoidLoginsuccess (Final user user) {You need to execute on the UI thread (New Runnable () { @Override public void run () {userloginview.tomainactivity (user); userloginview.hideloading ();}); }  @Override public void loginfailed () {//need to be executed on the UI thread ( new Runnable () { @Override  Public void run () {userloginview.showfailederror (); Userloginview.hideloading (); } }); } }); } public void clear () { Userloginview.clearusername (); Userloginview.clearpassword (); }} 

Note that the above code, our presenter complete the interaction between the two, then definitely need the implementation of the two classes. It's about 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.

OK, get an example after the decomposition of the above basic can be completed. The above is purely personal opinion, welcome to discuss and spit groove ~ has a nice day ~.

SOURCE Click to download

Public Number: Hongyangandroid
(Welcome attention, the first time to push the blog post information)

      • Https://
      • Https://
      • Https://
      • Http://
      • Http://
      • Http://

Talking about MVP in Android

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: 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.