Android Data Binding code practice (farewell to findViewById) (4), androiddatabinding

Source: Internet
Author: User
Tags android data binding

Android Data Binding code practice (farewell to findViewById) (4), androiddatabinding

Data Binding practice (1)
Data Binding Syntax Parsing (2)
Advanced Data Binding usage (III)
Well, after learning Data Binding in the first three articles, we can find that its power is as follows:

1. Use the MVVM mode to clear the entire project structure
2. Connecting views and models through ViewModel decouples views from the Model layer and performs their respective duties after layering for easy maintenance
3. Easy project testing
4. You can automatically generate a View object based on the id, and no longer use findViewById.

Well, I mentioned the benefits, and of course there are some bad points. After all, it was just launched this year. I have summarized two major shortcomings and I think it will be improved in future versions:

1. When Binding Data with Data Binding, subsequent Code cannot be written through the code prompt. All the Code must be written one by one, and the syntax check is only performed during compilation. This process is cumbersome.
2. Currently, Data Binding only supports one-way Binding and cannot be bound in two-way. Who can refuse to use it if two-way Binding is added in later versions?

The following shows how to use Data Binding in RecyclerView through a Demo:

Model Layer

There is only one User class that inherits from BaseObservable, adds @ Bindable annotation to the getter method, and adds policypropertychanged () to the setter method (), in this way, the UI update can be notified when data in the User is updated:

public class User extends BaseObservable{    private String userName;    private String userPassword;    private int userAge;    @Bindable    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;        notifyPropertyChanged(com.sunzxyong.binding.BR.userName);    }    @Bindable    public String getUserPassword() {        return userPassword;    }    public void setUserPassword(String userPassword) {        this.userPassword = userPassword;        notifyPropertyChanged(com.sunzxyong.binding.BR.userPassword);    }    @Bindable    public int getUserAge() {        return userAge;    }    public void setUserAge(int userAge) {        this.userAge = userAge;        notifyPropertyChanged(com.sunzxyong.binding.BR.userAge);    }    public User(String userName, String userPassword, int userAge) {        this.userName = userName;        this.userPassword = userPassword;        this.userAge = userAge;    }}
View Layer

Main Interface:

<layout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools">    <data>    </data>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical"        tools:context=".MainActivity">        <android.support.v7.widget.Toolbar            android:id="@+id/toolbar"            android:layout_width="match_parent"            android:layout_height="?attr/actionBarSize"            android:background="#03A9F4" />        <android.support.v7.widget.RecyclerView            android:id="@+id/recycler_view"            android:layout_width="match_parent"            android:layout_height="match_parent" />    </LinearLayout></layout>

Recycler_item:

<?xml version="1.0" encoding="utf-8"?><layout xmlns:android="http://schemas.android.com/apk/res/android">    <data>        <variable            name="user"            type="com.sunzxyong.binding.model.User"/>    </data>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_margin="5dp"        android:background="#009688"        android:gravity="center"        android:orientation="vertical">        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@{user.userName}"            android:textSize="20sp"            android:textColor="#ffffff" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@{user.userPassword}"            android:textSize="20sp"            android:textColor="#ffffff" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@{String.valueOf(user.userAge)}"            android:textSize="20sp"            android:textColor="#ffffff" />    </LinearLayout></layout>

User is bound to recycler_item...

ViewModel layer:

Set Toolbar and RecyclerView:
We get the Toolbar Control and RecyclerView control through the ActivityMainBinding object:

// Set Toolbar ActivityMainBinding mainBinding = DataBindingUtil. setContentView (this, R. layout. activity_main); mainBinding. toolbar. setTitle ("Android Data Binding code practice"); mainBinding. toolbar. setTitleTextColor (Color. WHITE); setsuppactionactionbar (mainBinding. toolbar); initData (); // sets RecyclerView mainBinding. recyclerView. setLayoutManager (new StaggeredGridLayoutManager (2, StaggeredGridLayoutManager. VERTICAL); MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter (this, users); mainBinding. recyclerView. setAdapter (adapter );

BindingHolder:

public class BindingHolder extends RecyclerView.ViewHolder {    private RecyclerItemBinding binding;    public BindingHolder(View itemView) {        super(itemView);    }    public RecyclerItemBinding getBinding() {        return binding;    }    public void setBinding(RecyclerItemBinding binding) {        this.binding = binding;    }}

MyRecyclerViewAdapter:

Public class MyRecyclerViewAdapter extends RecyclerView. adapter <BindingHolder> {private Context mContext; private List <User> users; private List <Integer> heights; public MyRecyclerViewAdapter (Context context, List <User> users) {this. mContext = context; this. users = users; initHeight ();} private void initHeight () {heights = new ArrayList <> (); for (int I = 0; I <users. size (); I ++) {heights. add (200 + (int) (300 * Math. random (); }}@ Override public BindingHolder onCreateViewHolder (ViewGroup parent, int viewType) {RecyclerItemBinding mItemBinding = DataBindingUtil. inflate (LayoutInflater. from (mContext), R. layout. recycler_item, parent, false); BindingHolder mHolder = new BindingHolder (mItemBinding. getRoot (); // get the root Layout View settings to ViewHolder mHolder. setBinding (mItemBinding); // sets mItemBinding to ViewHolder return mHolder;} @ Override public void onBindViewHolder (BindingHolder holder, int position) {ViewGroup. layoutParams params = holder. itemView. getLayoutParams (); params. height = heights. get (position); holder. itemView. setLayoutParams (params); // use holder. getBinding () obtains Binding Class User user = users. get (position); holder. getBinding (). setVariable (com. sunzxyong. binding. BR. user, user); // dynamically set data // holder. getBinding (). setUser (user); this method also works, because the User inherits from BaseObservable holder.getbinding(.exe cutePendingBindings (); // update the UI immediately} @ Override public int getItemCount () {return users. size ();}}

Effect:

Source Code address
Now, all functions of Android Data Binding are finished.
Google official documentation: https://developer.android.com/intl/zh-cn/tools/data-binding/guide.html

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger. Reprinted with the source: http://blog.csdn.net/u010687392

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.