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.

VC Concept ">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?

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. 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. 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
Package Com.xjp.androidmvcdemo.controller;import Android.app.dialog;import Android.app.progressdialog;import Android.os.bundle;import Android.support.v7.app.actionbaractivity;import Android.view.view;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;import Com.xjp.androidmvcdemo.r;import Com.xjp.androidmvcdemo.entity.weather;import Com.xjp.androidmvcdemo.entity.weatherinfo;import Com.xjp.androidmvcdemo.model.onweatherlistener;import Com.xjp.androidmvcdemo.model.weathermodel;import Com.xjp.androidmvcdemo.model.weathermodelimpl;public Class Mainactivity extends Actionbaractivity implements Onweatherlistener, View.onclicklistener {private Weathermodel weathe    Rmodel;    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;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Weathermodel = new Weathermodelimpl ();    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 = new ProgressDialog (this);    Loadingdialog.settitle (Loading the weather ...); }/** * Show results * * @param weather */public void Displayresult (weather weather) {Weatherinfo W        Eatherinfo = 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 ()) {R.id.btn_go:lo                Adingdialog.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 findview (int id) {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

Package com.xjp.androidmvcdemo.model;/** * Description: Request network Data interface * USER:XJP * DATE:2015/6/3 * time:15:40 */public Interf Ace Weathermodel {void GetWeather (String citynumber, Onweatherlistener listener);} .... package Com.xjp.androidmvcdemo.model;import Com.android.volley.response;import------ Com.android.volley.volleyerror;import Com.xjp.androidmvcdemo.entity.weather;import com.xjp.androidmvcdemo.volley.volleyrequest;/** * Description: Get weather information from the network interface implementation * USER:XJP * DATE:2015/6/3 * time:15:40 */p Ublic class Weathermodelimpl implements Weathermodel {@Override public void GetWeather (String citynumber, Final onw Eatherlistener listener) {/* data-tier operation */Volleyrequest.newinstance (). Newgsonrequest (Http://www.weather.com.cn/da                    ta/sk/+ citynumber +. html, Weather.class, new Response.listener () {@Override                            public void Onresponse (Weather Weather) {if (Weather! = null) {Listener.onsuccess (weather);                        } else {listener.onerror (); }}, new Response.errorlistener () {@Override PU                    Blic 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

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.

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.

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.

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.

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.