Design mode MVC for Android

Source: Internet
Author: User

The study of Android has been developed for more than 2 years, in this 2 years of learning, basic knowledge of Android. The more to the back of the study more difficult to feel, one is that Android has nothing to learn (since, in fact, there is a lot of knowledge science), and the network of many frameworks have helped us do too many things, we only need to draw the UI can be, feel Android development not too much technology gold. Recently idle to have nothing to do, began to summarize before the knowledge point, think whether should learn something else? It can't be confined to Android basics. A slow exploration found that in large project projects, a good framework, a good design pattern, can reduce a lot of work. So the next two blogs will learn about two of the most commonly used framework design patterns in Android: MVC and MVP.

MVC concept

The full name of MVC is the model View Controller, which is the abbreviation for the models-view-controller, a software design paradigm that organizes the code with a method of business logic, data, and interface display separation. Aggregating business logic into a single component does not require rewriting business logic while improving and personalizing the interface and user interaction. where m-layer processing data, business logic, and so on; v-Layer processing interface display results; The C-layer acts as a bridge to control the V-layer and M-layer communication to achieve the separation view display and the business logic layer. Speaking so much, listening to the feeling is very abstract, not much nonsense to say, we look at the MVC in the development of Android is how to use it!

MVC for Android

In Android development, the more popular development framework pattern is the MVC design pattern, the advantage of adopting MVC pattern is that it is easy to display the UI part and business logic, and data processing is separated. So what code in the Android project serves as the m,v,c role?

    1. M layer: Suitable for doing some business logic processing, such as database operations, network operations, complex algorithms, time-consuming tasks are processed in the model layer.
    2. V-layer: The display of the interface UI, the XML layout can be treated as a V-layer, and of course, the operating code that displays the results of the logical processing of the interface UI.
    3. C Layer: In Android, activity can be considered a controller, activity initiates business logic request processing, waits for business processing result, then notifies the view update interface.

Next we interpret MVC for Android through a small project that gets the weather forecast data. First the previous interface diagram:

Let's start writing code, starting with the activity implementation:

 PackageCom.xjp.androidmvcdemo.controller;ImportAndroid.app.Dialog;ImportAndroid.app.ProgressDialog;ImportAndroid.os.Bundle;Importandroid.support.annotation.Nullable;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportCOM.XJP.ANDROIDMVCDEMO.R;ImportCom.xjp.androidmvcdemo.entity.Weather;ImportCom.xjp.androidmvcdemo.entity.WeatherInfo;ImportCom.xjp.androidmvcdemo.model.OnWeatherListener;ImportCom.xjp.androidmvcdemo.model.WeatherModel;ImportCom.xjp.androidmvcdemo.model.WeatherModelImpl;/** * Description: * USER:XJP * DATE:2015/6/3 * time:16:26 * * Public  class weatheractivity extends actionbaractivity {    PrivateDialog Loadingdialog;PrivateEditText Citynoinput;PrivateTextView City;PrivateTextView Cityno;PrivateTextView temp;PrivateTextView WD;PrivateTextView ws;PrivateTextView SD;PrivateTextView WSE;PrivateTextView time;PrivateTextView NJD;@Override    protected void onCreate(@Nullable Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); }/** * Initialize view * /    Private void Initview() {citynoinput = (EditText) Findviewbyid (r.id.et_city_no);        City = (TextView) Findviewbyid (r.id.tv_city);        Cityno = (TextView) Findviewbyid (r.id.tv_city_no);        temp = (TextView) Findviewbyid (r.id.tv_temp);        WD = (TextView) Findviewbyid (R.ID.TV_WD);        WS = (TextView) Findviewbyid (R.ID.TV_WS);        SD = (TextView) Findviewbyid (R.ID.TV_SD);        WSE = (TextView) Findviewbyid (R.id.tv_wse);        Time = (TextView) Findviewbyid (r.id.tv_time);        NJD = (TextView) Findviewbyid (R.ID.TV_NJD); Loadingdialog =NewProgressDialog ( This); Loadingdialog.settitle ("Load the weather ..."); Findviewbyid (R.id.btn_go). Setonclicklistener ( This); }/** * Show Results * * @param Weather * *     Public void Displayresult(Weather Weather)        {Weatherinfo weatherinfo = Weather.getweatherinfo ();        City.settext (Weatherinfo.getcity ());        Cityno.settext (Weatherinfo.getcityid ());        Temp.settext (Weatherinfo.gettemp ());        Wd.settext (WEATHERINFO.GETWD ());        Ws.settext (Weatherinfo.getws ());        Sd.settext (WEATHERINFO.GETSD ());        Wse.settext (Weatherinfo.getwse ());        Time.settext (Weatherinfo.gettime ());    Njd.settext (WEATHERINFO.GETNJD ()); }}@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.btn_go:loadingdialog.show ();//Perform network requests                 Break; }    }

As you can see from the code above, the activity is responsible for the response events of the view UI and the request results view display. The above code seems to be fine, but from the extensibility of the code to maintainability considerations, there is a downside to writing code: When the customer's view view shows that the requirements have changed, we have to modify the code in the activity to modify the view view display. When the interface display modification is large, the activity of the code changes are also very large, so that the activity code is bloated, not conducive to maintenance, it is also possible to modify the activity when the other part of the code error in the activity. Therefore, we do not advocate to write the view interface display in activity. Based on the MVC design pattern development, the view view is detached, reducing the burden on the activity and allowing the activity to assume the controller role. Look at the code implementation as follows:

Look at the project catalog structure

View views
 PackageCom.xjp.androidmvcdemo.view;ImportAndroid.app.Dialog;ImportAndroid.app.ProgressDialog;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportCOM.XJP.ANDROIDMVCDEMO.R;ImportCom.xjp.androidmvcdemo.entity.Weather;ImportCom.xjp.androidmvcdemo.entity.WeatherInfo;/** * Description: Display the weather information to view * USER:XJP * DATE:2015/6/3 * time:14:55 * * Public  class displayweatherinfoview {    PrivateActionbaractivity activity; Requestweatherview irequest;PrivateDialog Loadingdialog;PrivateEditText Citynoinput;PrivateTextView City;PrivateTextView Cityno;PrivateTextView temp;PrivateTextView WD;PrivateTextView ws;PrivateTextView SD;PrivateTextView WSE;PrivateTextView time;PrivateTextView NJD; Public Displayweatherinfoview(actionbaractivity activity, Requestweatherview irequest) { This. activity = activity; This. irequest = Irequest;    Initview (); }/** * Initialize view * /    Private void Initview() {citynoinput = (EditText) Activity.findviewbyid (r.id.et_city_no);        City = (TextView) Activity.findviewbyid (r.id.tv_city);        Cityno = (TextView) Activity.findviewbyid (r.id.tv_city_no);        temp = (TextView) Activity.findviewbyid (r.id.tv_temp);        WD = (TextView) Activity.findviewbyid (R.ID.TV_WD);        WS = (TextView) Activity.findviewbyid (R.ID.TV_WS);        SD = (TextView) Activity.findviewbyid (R.ID.TV_SD);        WSE = (TextView) Activity.findviewbyid (R.id.tv_wse);        Time = (TextView) Activity.findviewbyid (r.id.tv_time);        NJD = (TextView) Activity.findviewbyid (R.ID.TV_NJD); Loadingdialog =NewProgressDialog (activity); Loadingdialog.settitle ("Load the weather ..."); Activity.findviewbyid (R.id.btn_go). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v)                {loadingdialog.show ();            Irequest.sendrequest (Citynoinput.gettext (). toString (). Trim ());    }        }); }/** * Show Results * * @param Weather * *     Public void Displayresult(Weather Weather)        {Weatherinfo weatherinfo = Weather.getweatherinfo ();        City.settext (Weatherinfo.getcity ());        Cityno.settext (Weatherinfo.getcityid ());        Temp.settext (Weatherinfo.gettemp ());        Wd.settext (WEATHERINFO.GETWD ());        Ws.settext (Weatherinfo.getws ());        Sd.settext (WEATHERINFO.GETSD ());        Wse.settext (Weatherinfo.getwse ());        Time.settext (Weatherinfo.gettime ());    Njd.settext (WEATHERINFO.GETNJD ()); }/** * Hide Progress dialog box * /     Public void Hideloadingdialog() {Loadingdialog.dismiss (); }}

We will control the view interface a Displayweatherinfoview class that implements the view initialization and display of the view interface results, as well as the interface of the view response event. All the interface operations are in this class.

Controller controllers

Next look at how the activity calls the Displayweatherinfoview class.

 PackageCom.xjp.androidmvcdemo.controller;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.widget.Toast;ImportCOM.XJP.ANDROIDMVCDEMO.R;ImportCom.xjp.androidmvcdemo.model.OnWeatherListener;ImportCom.xjp.androidmvcdemo.entity.Weather;ImportCom.xjp.androidmvcdemo.model.WeatherModel;ImportCom.xjp.androidmvcdemo.model.WeatherModelImpl;ImportCom.xjp.androidmvcdemo.view.DisplayWeatherInfoView;ImportCom.xjp.androidmvcdemo.view.RequestWeatherView; Public  class mainactivity extends actionbaractivity  implements  Requestweatherview, onweatherlistener {    PrivateDisplayweatherinfoview Displayview;Private StaticWeathermodel Weathermodel =NULL;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Displayview =NewDisplayweatherinfoview ( This, This);if(NULL= = Weathermodel) {Weathermodel =NewWeathermodelimpl (); }    }@Override     Public void SendRequest(String number) {Weathermodel.getweather (number, This); }@Override     Public void onsuccess(Weather Weather)        {Displayview.hideloadingdialog ();    Displayview.displayresult (weather); }@Override     Public void OnError() {displayview.hideloadingdialog (); Toast.maketext ( This,"Get weather information failed", Toast.length_short). Show (); }}

The above code shows that activity holds the Displayweatherinfoview object reference and implements the Requestweatherview control response event interface. When a view view has a similar user click Response Event, the interface communicates to notify Activity,view that a user response event occurred, allowing the activity to do the appropriate processing, when the activity acts as a controller role to send the user's response request to Model layer to allow the model layer to handle network requests. Therefore, the activity also holds the Model object reference Weathermodelimpl.

Model Models

Take a look at the Weathermodelimpl code implementation

 PackageCom.xjp.androidmvcdemo.model;/** * Description: Request network Data interface * USER:XJP * DATE:2015/6/3 * time:15:40 * * Public  interface weathermodel {    voidGetWeather (String citynumber, Onweatherlistener listener);} ................ PackageCom.xjp.androidmvcdemo.model;ImportCom.android.volley.Response;ImportCom.android.volley.VolleyError;ImportCom.xjp.androidmvcdemo.entity.Weather;ImportCom.xjp.androidmvcdemo.volley.VolleyRequest;/** * Description: Get weather information from the network interface implementation * USER:XJP * DATE:2015/6/3 * time:15:40 * * Public  class Weathermodelimpl implements Weathermodel {    @Override     Public void GetWeather(String Citynumber,FinalOnweatherlistener listener) {/ * Data-tier operation * /Volleyrequest.newinstance (). Newgsonrequest ("http://www.weather.com.cn/data/sk/"+ Citynumber +". html", Weather.class,NewResponse.listener<weather> () {@Override                     Public void Onresponse(Weather Weather) {if(Weather! =NULL) {listener.onsuccess (weather); }Else{Listener.onerror (); }                    }                },NewResponse.errorlistener () {@Override                     Public void Onerrorresponse(Volleyerror error)                    {Listener.onerror ();    }                }); }}

The above code shows that a Weathermodel model interface is designed, and then the interface Weathermodelimpl class is implemented. As for this, why not just design a getweather () method directly into a class to request network data? You consider this: now the network request in the code is implemented using the volley framework, and if the boss does not want you to use the Afinal framework to implement network requests, how do you solve the problem? Is it possible to modify the implementation of the GetWeather () method? No no, this modification not only destroys the previous code, but also is not conducive to maintenance, considering the future code extension and maintenance, we choose to design the interface to solve a problem, we implement another Weathermodelwithafinalimpl class, Inherit from Weathermodel, rewrite the method inside, this not only preserves the previous Weathermodelimpl class request network way, but also increases the Weathermodelwithafinalimpl class request way. The activity call code does not require any modification.

MVC Usage Summary
    1. With the MVC design pattern, this weather forecast small project has a very good scalability and maintainability, when the need to change the UI display, do not need to modify the Contronller (Controller) activity of the Code and Model (model) Weathermodel models of Business logic code , which separates the business logic and the interface display very well.

    2. In the Android project, the business logic, data processing, etc. served as the Model (modeling) role, the XML interface display, and so on as the view (view) role, activity as the Contronller (Controller) role. The Contronller (Controller) is the role of an intermediate bridge, which works through interface communication to coordinate view (view) and model (models), and plays a role in communication between the two.

    3. When is it appropriate to use MVC design patterns? Of course a small project and no need to modify the requirements of the MVC framework to design, so instead of the code over-design, the code is bloated. Generally in large projects, and business logic processing complex, page display is more, the need for modular design projects using MVC has enough advantages.

    4. Advantages of MVC:

      (1) Low coupling. The so-called coupling is the degree of association between module code. With the MVC framework, the view layer and model layer can be separated very well, so as to realize the purpose of decoupling, so the coupling is low and the interaction between module code is reduced.

      (2) scalability is good. Because of the low coupling and the need to add, the extension code reduces the number of changes to the previous code and reduces the incidence of bugs.

      (3) module responsibilities are clearly divided. The main partition layer M,v,c three modules, which facilitates the maintenance of the code.

Reprint Annotated Source: http://blog.csdn.net/feiduclear_up/article/details/46343801 Ruins of the tree blog

Source code Sample Download

Design mode MVC for 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: 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.