Android MVP Mode Learning (ii)----DATA binding combination

Source: Internet
Author: User
Tags android data binding

The company project has recently been re-constructed with the MVP model, the reconstructed project is intuitive, the code is highly reusable and easy to debug and maintain.

Then the supervisor let me to understand MVC,MVP, mvvm,data binding related knowledge, so I have the following this blog. Resources:
Choose the Gospel of phobia! Teach you to recognize MVC,MVP and MVVM.

Fully Master Android Data Binding
Thanks to the theory and technical support of these two articles, thanks to these great gods.

OK, start today's theme.
About the MVP model and the MVVM model, I think it is not a beginner in a few short sentences to be able to say clearly, we do not have to dwell on this. The words of the Great God "the real best practices are all people think of." Why don't we combine the MVP and MVVM features: Mvp+data binding, still using presenter to do the communication with the model layer, and using the data Binding to easily bind data.

A data-binding framework published by the Android team at the Google IO Conference at data binding--2015. You can later bind the data directly in the layout layouts XML file without having to set the data through the Findviewbyid or annotation framework.

Take a look at the application of Mvp+data binding in the project:

Click button, request load network data, two seconds later, the simulated data is displayed in TextView.

1. Preparatory work
Create a new Project to ensure that Android's Gradle plugin version is not less than 1.5.0-ALPHA1:

‘com.android.tools.build:gradle:1.5.0‘

Then modify the Build.gradle of the corresponding module (modules):

dataBinding {    true}

2. Data Objects
There are two kinds of data objects here, one is normal data object, one is bound data object, can update data automatically.

Let's look at the first type:

/** * Created by Tangyangkai on 16/4/27. * * Public  class User{    PrivateString FirstName;PrivateString LastName; PublicStringGetfirstname() {returnFirstName; } Public void Setfirstname(String firstName) { This. firstName = FirstName; } PublicStringGetlastname() {returnLastName; } Public void Setlastname(String lastName) { This. lastName = LastName; }}

A simple user, two attributes, and its getter and setter.

3. Layout files

<layout xmlns:android="Http://schemas.android.com/apk/res/android">    <data>        <variablename= "user"type=" Com.example.tangyangkai.myapplication.User ">                        </variable>    </Data>    <linearlayoutandroid:layout_width="Match_parent"android:layout_height ="Match_parent"android:orientation="vertical">                                <buttonandroid:layout_width="Wrap_content"android:layout_height ="Wrap_content"android:onclick="getwebmsg"android:text=  "Analog Request network data" />                                                        <TextViewandroid:layout_width="Wrap_content"android:layout_height= "Wrap_content" Android:text="Last name:" />                                            <TextViewandroid:layout_width="Wrap_content"android:layout_height ="Wrap_content"android:text="@{user.firstname}" />                                            <TextViewandroid:layout_width="Wrap_content"android:layout_height= "Wrap_content" Android:text="Name:" />                                            <TextViewandroid:layout_width="Wrap_content"android:layout_height ="Wrap_content"android:text="@{user.lastname}" />                                        </linearlayout></layout>

(1.)Data node: Once the data Binding is used, the XML layout file is no longer used to simply present the UI elements, and the variables used for UI elements need to be defined. Therefore, its root node is no longer a viewgroup, but instead becomes layout, and a new node data is added. The data node acts like a bridge, binding the model to the UI (view) and building the path between the view and the model.
(2.) affirms variable:

<data><variable      name="user"      type="com.example.tangyangkai.myapplication.User">            </variable></data>

A variable is declared in the data node of the XML layout file, which provides data for the UI element (for example, TextView android:text), and then binds the data obtained in the Java code to the variable. Where the type attribute is the User class that we define in the Java file.
(3.) use variable:

            <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@{user.firstName}" />

After the data is bound to Variable, the UI elements of the XML can be used directly.

4.Activity implementations

 Public  class fiveactivity extends appcompatactivity  implements  Stringview {    PrivateStringpresenter Mstringpresenter; Activityfivebinding binding;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Mstringpresenter =NewStringpresenter ( This); binding = Databindingutil.setcontentview ( This, r.layout.activity_five); }//Request network data     Public void getwebmsg(View view)    {Mstringpresenter.seturl (); }@Override     Public void showstring(String firstName, String lastName) {User User =NewUser ();        User.setfirstname (FirstName);        User.setlastname (LastName);    Binding.setuser (user); }}

(1.) activityfivebinding is automatically generated by the framework, where the set method is generated based on the variable name.
(2.) Modify the Fiveactivity OnCreate method, replace the Setcontentview () with Databindingutil.setcontentview ()
(3.) Creates a user object that passes the data obtained from the network through the set method to the user and binds to the variable by binding.setuser (user).

At this point, the data binding process using the first object has gone through, in fact the core is to declare variable, bind variable, use variable. the second data object is the same, but it is a bit different when binding variable.

5. Second type of data

/** * Created by Tangyangkai on 16/4/27. * * Public  class User extends baseobservable{    PrivateString FirstName;PrivateString LastName;@Bindable     PublicStringGetfirstname() {returnFirstName; } Public void Setfirstname(String firstName) { This. firstName = FirstName;    Notifypropertychanged (Br.firstname); }@Bindable     PublicStringGetlastname() {returnLastName; } Public void Setlastname(String lastName) { This. lastName = LastName;    Notifypropertychanged (Br.lastname); }}

(1.) to achieve the binding of data objects, Android native provides a packaged class--baseobservable, and implements the listener registration mechanism, we only need to inherit baseobservable.
(2.) BR is a class generated during the compilation phase, similar in function to R.java, with the @Bindable tag getter method automatically generates a entry in the BR.
(3.) When the data changes, the Notifypropertychanged (Br.firstname) method is called, notifying the system br.firstname that the entry data has changed and then updates the UI.

 Public  class fiveactivity extends appcompatactivity  implements  Stringview {    PrivateStringpresenter Mstringpresenter; User User =NewUser ();@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Mstringpresenter =NewStringpresenter ( This); activityfivebinding binding = Databindingutil.setcontentview ( This, r.layout.activity_five);    Binding.setuser (user); }//Request network data     Public void getwebmsg(View view)    {Mstringpresenter.seturl (); }@Override     Public void showstring(String firstName, String lastName)        {user.setfirstname (firstName);    User.setlastname (LastName); }}

Unlike the first data object, variable data binding is done at initialization time. Once the network data has been successfully obtained, the data and UI updates are performed internally as long as they are passed directly to user.

6.MVP of code

Presenter Layer

/** * Created by Tangyangkai on 16/4/11. * Presenter as the middle layer, holding the view and model references, processing the data of the model layer, controlling the view layer display */ Public  class stringpresenter implements Stringmodel. Getmsglistener {    PrivateStringview Stringview;PrivateStringmodel Stringmodel; Public Stringpresenter(Stringview Stringview) { This. Stringview = Stringview; Stringmodel =NewStringmodel (); }//Provide request data method to view layer     Public void SetUrl() {stringmodel.getwebmsg ( This); }//Pass the data returned by the model layer to the view    @Override     Public void getmsgsuccess(String firstName, String lastName) {Stringview.    Showstring (FirstName, lastName); }}

Model Layer

/** * Created by Tangyangkai on 16/4/11. * Simulation request data, actual combat based on the return result processing * / Public  class stringmodel {     Public  interface getmsglistener {        voidGetmsgsuccess (String firstName, string lastName); } Public void getwebmsg(Getmsglistener Listener) {//Analog network data request        Try{Thread.Sleep ( -); }Catch(Interruptedexception e)        {E.printstacktrace (); } listener.getmsgsuccess ("Tang","Yangkai"); }}

The previous blog about the use of the MVP said very clearly, here is not explained in detail.
Android MVP Mode Learning (I.)--Cognition and use

The high-level usage of the data binding and considerations, the first two articles introduced in detail, we can savor.

Regarding these patterns and frameworks, the benevolent see, in fact, is to minimize the coupling of the program and improve the reusability of the code. The above is a record of their recent study of these framework patterns of some of the experience, there are inappropriate welcome to point out that together progress.

The company opened a new project, ready to put in a new battle O (∩_∩) o~

Android MVP Mode Learning (ii)----DATA binding combination

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.