Use of the framework mode MVP in Android and the framework mode mvpandroid

Source: Internet
Author: User

Use of the framework mode MVP in Android and the framework mode mvpandroid

In the previous article, I learned how to use the MVC Framework in Android. I don't know what the MVC Framework pattern is. Here, the Framework pattern MVC is used in Android. In fact, Google's Android Development Team encourages developers to develop projects using the MVC framework model. We usually write code to develop projects using the MVC framework model more or less, for example, Google's Volley network request framework, which exited by itself, follows the MVC framework. We can understand that the Volley framework is a model in MVC, that is, network data processing, without any association with the View. It also complies with the separation of views and models. You may think that the MVC framework is very useful and can meet the needs of any project development. It is good, but you will find from the previous blog that, the Controller and View display are embodied in a class Activity, while the Activity in Android plays the role of Controller. If the interface operations are complicated and the View display is complex, therefore, we have to add more View display operations to the Activity. This naturally increases the amount of code for the Activity, and leads to too many tasks and logic processes undertaken by the Activity, with unclear responsibilities. This article introduces another framework model MVP.

MVP

MPV evolved from the classic MVC model, and its basic ideas are the same. M is a model that provides business data. P is similar to C in MVC, and is a Presenter controller for logical processing. V is the View that displays data. There is a major difference between MVPs and MVC: In MVPs, views do not directly use models. Communication between them is implemented through Presenter (Controller in MVC, all interactions occur within the Presenter. In MVC, the View reads data from the direct Model rather than through the Controller.

MVC Framework
MVP framework

From the above frame chart, we can see that the biggest difference between MVC and MVP is the relationship between Model and View. In the MVC Framework, a View can directly read data from the Model. If the Model data changes, the View data display is changed accordingly. In MVP, there is no connection between the Model and View. They are two completely independent modules. When the Model changes data, the Presenter notifies the View of corresponding UI changes. Therefore, I personally think that MVP is the separation between the View and the Model, that is, the business data processing of the Model and the View display are not associated.

MVP for Android

In the Andorid project, we use Activity as the controller in MVC to separate the Model and View. However, in the MVP framework mode, Activity is usually used as the View layer, in the MVC framework mode, the Activity and View display are closely related. The Activity contains a large number of View display code. If the boss says that the View display needs to be modified someday, at this time, do you feel that you need to modify a lot of code in the Activity? In this way, the control logic in the Activity will be destroyed, and the Activity will assume too many responsibilities. According to the single responsibility principle, Activity mainly plays a role in user interaction, that is, receiving user input and displaying request results. Therefore, the MVP framework can be used to reduce the Activity's responsibilities. Let's see how the Android project is implemented!

Take the previous small weather forecast project as an example:

Model

Same as the MVC Framework, the Model process data code remains unchanged.

/*** Created by xjp 2015-6-7 * weather Model interface */public interface WeatherModel {void loadWeather (String cityNO, OnWeatherListener listener );}......... /*** Created by xjp on 2015/6/7. * weather Model implementation */public class WeatherModelImpl implements WeatherModel {@ Override public void loadWeather (String cityNO, final OnWeatherListener listener) {/* data layer operation */VolleyRequest. newInstance (). newGsonRequest ("http://www.w Eather.com.cn/data/sk/ "+ cityNO +". html ", Weather. class, new Response. Listener <Weather> () {@ Override public void onResponse (Weather weather) {if (weather! = Null) {listener. onSuccess (weather);} else {listener. onError () ;}}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {listener. onError ();}});}}

The OnWeatherListener interface calls back the data processed by the Model to the Presenter controller.

Presenter Controller
/*** Created by xjp on 2015/6/7. * weather Presenter interface */public interface WeatherPresenter {/*** obtain the weather logic */void getWeather (String cityNO );}.......... /*** Created by xjp on 2015/6/7. * implemented at the Presenter layer, called back to the Model layer, and changed the status of the View layer, make sure that the Model layer does not directly operate on the View layer */public interface OnWeatherListener {/*** callback when the call succeeds ** @ param weather */void onSuccess (Weather weather ); /*** callback upon failure, simple processing, nothing done */void onError ();}......... package org. rocko. demos. mvp. presenter. impl; import org. rocko. demos. mvp. model. weatherModel; import org. rocko. demos. mvp. model. entity. weather; import org. rocko. demos. mvp. model. impl. weatherModelImpl; import org. rocko. demos. mvp. presenter. onWeatherListener; import org. rocko. demos. mvp. presenter. weatherPresenter; import org. rocko. demos. mvp. ui. view. weatherView;/*** Created by xjp on 2015/6/7. * weather Presenter implementation */public class WeatherPresenterImpl implements WeatherPresenter, OnWeatherListener {/* Presenter as the middle layer, holding reference of View and Model */private WeatherView weatherView; private WeatherModel weatherModel; public WeatherPresenterImpl (WeatherView weatherView) {this. weatherView = weatherView; weatherModel = new WeatherModelImpl () ;}@ Override public void getWeather (String cityNO) {weatherView. showLoading (); weatherModel. loadWeather (cityNO, this) ;}@ Override public void onSuccess (Weather weather) {weatherView. hideLoading (); weatherView. setWeatherInfo (weather) ;}@ Override public void onError () {weatherView. hideLoading (); weatherView. showError ();}}

From the code, we can see that the Presenter controller holds both WeatherModel and WeatherView objects and implements the OnWeatherListener interface to retrieve Model data. Therefore, WeatherPresenterImpl sends data requests to WeatherModel, then, the OnWeatherListener interface is used to obtain the request results. The results are displayed in the View of the Activity through the WeatherView interface. In this way, the Model and View are completely separated. In this case, if you need to modify the Model, it will not affect the modification of the View code. Likewise, when modifying the View layer, you do not need to modify the Model layer. This means that the Model and View do not know each other's existence and communicate with each other through the intermediate controller Presenter.

View

First define a View display interface WeatherView

/** * Created by xjp on 2015/6/7. */public interface WeatherView {    void showLoading();    void hideLoading();    void showError();    void setWeatherInfo(Weather weather);}

Then implement the WeatherView interface of the Activity.

/***** Weather interface */public class WeatherActivity extends BaseActivity implements WeatherView, View. onClickListener {private Dialog loadingDialog; private EditText cityNOInput; private TextView city; private TextView cityNO; private TextView temp; private TextView wd; private TextView ws; private TextView sd; private TextView wse; private TextView time; private TextView njd; private WeatherPresenter weatherPresenter; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); init ();} private void init () {cityNOInput = findView (R. id. et_city_no); city = findView (R. id. TV _city); cityNO = findView (R. id. TV _city_no); temp = findView (R. id. TV _temp); wd = findView (R. id. TV _WD); ws = findView (R. id. TV _WS); sd = findView (R. id. TV _SD); wse = findView (R. id. TV _WSE); time = findView (R. id. TV _time); njd = findView (R. id. TV _njd); findView (R. id. btn_go ). setOnClickListener (this); weatherPresenter = new WeatherPresenterImpl (this); // input WeatherView loadingDialog = new ProgressDialog (this); loadingDialog. setTitle ("loading weather... ") ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. btn_go: weatherPresenter. getWeather (cityNOInput. getText (). toString (). trim (); break; }}@ Override public void showLoading () {loadingDialog. show () ;}@ Override public void hideLoading () {loadingDialog. dismiss () ;}@ Override public void showError () {// Do something Toast. makeText (getApplicationContext (), "error", Toast. LENGTH_SHORT ). show () ;}@ Override public void setWeatherInfo (Weather weather) {WeatherInfo = weather. getWeatherinfo (); city. setText (info. getCity (); cityNO. setText (info. getCityid (); temp. setText (info. getTemp (); wd. setText (info. getWD (); ws. setText (info. getWS (); sd. setText (info. getSD (); wse. setText (info. getWS (); time. setText (info. getTemp (); njd. setText (info. getNjd ());}}

Therefore, the Activity is freed from the Controller in MVC. This Activity mainly displays views and interacts with users. Each Activity can implement the View Interface WeatherView based on different display views.

Summary

Source Code address download: Source Code address

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.