Frame mode MVC usage in 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 framework pattern, the advantage of adopting MVC pattern is that it is easy to display and business logic of UI interface, 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 access operations, network operations, complex algorithms, time-consuming tasks are processed in the model layer.
    2. V Layer: The portion of the application layer that handles the display of data, and the XML layout can be treated as a V-layer, showing the data results of the model layer.
    3. Layer C: In Android, activity handles user interaction issues, so you can think of activity as a controller, Activity reads data from the V-view layer (eg. reads data from the current EditText control), controls user input (input to the Eg.edittext control data), and sends data requests to model (eg. initiating a network request, etc.).

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

Controller controllers
 PackageCom.xjp.androidmvcdemo.controller;ImportAndroid.app.Dialog;ImportAndroid.app.ProgressDialog;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast;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; Public  class mainactivity extends actionbaractivity  implements  Onweatherlistener, View. Onclicklistener {    PrivateWeathermodel Weathermodel;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(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Weathermodel =NewWeathermodelimpl ();    Initview (); }/** * Initialize view * /    Private void Initview() {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); Loadingdialog =NewProgressDialog ( This); Loadingdialog.settitle ("Load the weather ..."); }/** * 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 (); }@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.btn_go:loadingdialog.show (); Weathermodel.getweather (Citynoinput.gettext (). toString (). Trim (), This); Break; }    }@Override     Public void onsuccess(Weather Weather)        {Hideloadingdialog ();    Displayresult (weather); }@Override     Public void OnError() {hideloadingdialog (); Toast.maketext ( This,"Get weather information failed", Toast.length_short). Show (); }Private<t extends View> TFindview(intID) {return(T) Findviewbyid (ID); }}

As can be seen from the above code, activity holds the object of the Weathermodel model, when the user has clicked button interaction, activity as controller control layer to read the View view layer Edittextview data, The data request is then initiated to the model models, that is, the method Getweathre () method that invokes the Weathermodel object. When the model is finished processing the data, the view layer is notified by the interface onweatherlistener that the data processing of the view layer is finished, and the UI of the view is updated. The view layer then calls the Displayresult () method to update the UI. At this point, the entire MVC framework process is reflected in the activity.

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. The Controller director activity calls the method in the Weathermodelimpl class to initiate a network request and then notifies the view layer to update the UI by implementing the Onweatherlistener interface to obtain the result of the network request. The activity then separated the view view display from the Model data processing. Activity acting as Contronller completed the coordination between model and view.

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. In the MVC pattern, we found that the controller activity is primarily decoupled, separating the view view from model models, although the activity interacts, there are many display codes for the view UI in the activity. Therefore, the view view and the activity controller are not completely detached, meaning that part of the view and Contronller controller activity is bound to a class.

    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/46363207 Ruins of the tree blog

Source code Sample Download

Frame mode MVC usage 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: 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.