DATA BINDING TRONG ANDROID

Trong bài viết này, mình sẽ hướng dẫn các bạn sử dụng Data Binding LibraryLibrary trong android để đổ dữ liệu thẳng vào view thông qua file xml, bỏ qua bước findViewById(). Điều này giúp ích trong trường hợp project của bạn có nhiều trường thông tin khác nhau. Thay vì phải gán giá trị và findViewById() thì chúng ta có thể dùng Data Binding.

Để dễ hiểu hơn, mình sẽ làm một ví dụ đơn giản áp dụng Data Binding để đổ dữ liệu lên RecyclerViewRecyclerView.

RecyclerView là một thư viện hổ trợ trong Android gần giống với ListView mà mình đã từng nói đến trong bài Add section.

Đầu tiên là mình tạo một project mới và làm theo các bước như sau:

1. Cấu hình Data Binding và RecyclerView vào project

Chúng ta vào thẻ build.gradle (app module) copy dòng code sau để cấu hình môi trường cho data binding:

android {
    ....
    dataBinding {
        enabled = true
    }
}

Sau đó là add RecyclerView, cũng trong thr build.gradle (app module) add dòng code:

dependencies {
    ....
    compile 'com.android.support:recyclerview-v7:25.2.0'
}

Tại activity_main.xml chúng ta nhúng RecyclerView vào:

//activity_main.xm
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hungnguyen.databindingexample.MainActivity"
    android:padding="16dp">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_item">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

2. Tạo class model và đỗ dữ liệu thông qua data binding

Class model User chứa trường thông tin là Name và Job:

public class User {
    private String Name;
    private String Job;

    public User(String name, String job) {
        Name = name;
        Job = job;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getJob() {
        return Job;
    }

    public void setJob(String job) {
        Job = job;
    }
}

Tạo file xml hiển thị từng item trong RecyclerView và đỗ dữ liệu thông qua data bind:

//list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="user"
            type="com.example.hungnguyen.databindingexample.User" />
    </data>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:text="Name"
                android:textSize="22sp" />

            <TextView
                android:id="@+id/txtDisplayName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{user.getName}"
                android:textSize="22sp" />

        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:text="Job"
                android:textSize="22sp" />

            <TextView
                android:id="@+id/txtAge"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{user.getJob}"
                android:textSize="22sp" />
        </LinearLayout>

    </LinearLayout>
</layout>

Các bạn chú ý 2 chổ này

<data>
        <variable
            name="user"
            type="com.example.hungnguyen.databindingexample.User" />
    </data>
android:text="@{user.getName}"

name ở đây là tên biến và type là đường dẫn đến class (các bạn có thể copy package name và thêm ".User") còn ở trong thuộc tính "text" ta gán data cho nó là user (mục name), getName (hàm đổ data Name trong class User khai báo ở mục type).

Vậy là chúng ta đã hiểu cách đỗ dữ liệu thông qua xml là như thế nào rồi đấy.

3. Tạo Adapter và đổ vào RecyclerView

Đầu tiên là tạo một class cấu hình cho RecyclerView, class này sẽ extends RecyclerView.ViewHolder và chúng ta sẽ đổ dữ liệu từ class User vào RecyclerView.

package com.example.hungnguyen.databindingexample;

import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.example.hungnguyen.databindingexample.databinding.ListItemBinding;

/**
 * Created by HungNguyen on 3/13/17.
 */

public class UserViewHolder extends RecyclerView.ViewHolder {

    private ListItemBinding binding;

    public UserViewHolder(View itemView) {
        super(itemView);
        binding = DataBindingUtil.bind(itemView);
    }

    public void bind(User user){
        binding.setUser(user);
    }
}

Ở đây mình lưu ý một chổ là biến ListItemBinding là do android studio tự động tạo ra dựa trên layout item của RecyclerView (ở đây layout đó mình đặt tên là list_item).

Tiếp theo, tạo adapter và implement những hàm cần thiết vào để gắn data vào RecyclerView.

package com.example.hungnguyen.databindingexample;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by HungNguyen on 3/13/17.
 */

public class UserAdapter extends RecyclerView.Adapter<UserViewHolder> {
    final List<User> users;

    public UserAdapter(List<User> users) {
        this.users = users;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.list_item, parent, false);
        return new UserViewHolder(view);
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        User user = users.get(position);
        holder.bind(user);
    }

    @Override
    public int getItemCount() {
        return users.size();
    }
}

Vậy là xong Adapter, giờ đến MainActivity chúng ta gọi RecyclerView và tạo dữ liệu cho class User rồi gắn vào RecyclerView

public class MainActivity extends AppCompatActivity {

    private RecyclerView list;
    private UserAdapter userAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list = (RecyclerView) findViewById(R.id.user_item);

        list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        User user1 = new User("Barry Allen", "Flash");
        User user2 = new User("Jennifer Lawrence", "Writer");
        User user3 = new User("Harry Poster", "Magical");

        ArrayList<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        userAdapter = new UserAdapter(userList);
        list.setAdapter(userAdapter);
    }
}

Run App và đây là kết quả

Trên đây là một ví dụ đơn giản về Data Binding, còn rất nhiều kỹ thuật Data Binding khác, các bạn có thể tham khảo thêm tại đây.

Goodluck!!!

by HungNguyen

results matching ""

    No results matching ""