通過Data Binding為RecyclerView打造通用Adapter

fansofandroid發表於2016-07-18

我們使用Data Binding庫一步步為RecyclerView打造通用的Adapter,今天我們先來編寫單一Item時的Adapter:SimpleAdapter。至於如何在專案中新增Data Binding庫,在次不再涉及,敬請自行Google或Android DataBinding介紹

第一步:通用的ViewHolder

package com.dfsebook.myrecycleradapter.view;

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

/**
 * Created by Administrator on 16-7-18.
 */
public class ViewHolder extends RecyclerView.ViewHolder{

   private ViewDataBinding binding;

    public ViewDataBinding getBinding() {
        return binding;
    }

    public void setBinding(ViewDataBinding binding) {
        this.binding = binding;
    }

    public ViewHolder(View itemView) {
        super(itemView);
    }
}

第二步:通用Adapter

package com.dfsebook.myrecycleradapter.adapter;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.dfsebook.myrecycleradapter.view.ViewHolder;

import java.util.List;

/**
 * Created by Administrator on 16-7-18.
 */
public class SimpleAdapter<T> extends RecyclerView.Adapter<ViewHolder>{

    private List<T> mDatas;

    private int layoutId;

    private int brId;

    public SimpleAdapter(List<T> mDatas, int layoutId, int brId) {
        this.mDatas = mDatas;
        this.layoutId = layoutId;
        this.brId = brId;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, layoutId, parent, false);
        ViewHolder viewHolder = new ViewHolder(binding.getRoot());
        viewHolder.setBinding(binding);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.getBinding().setVariable(brId,mDatas.get(position));
        holder.getBinding().executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }
}

至此準備工作基本結束,下面我們通過一個例子運用一下SimpleAdapter。

一、準備Bean:Student

package com.dfsebook.myrecycleradapter.bean;

/**
 * Created by Administrator on 16-7-18.
 */
public class Student {

    private int resId;

    private String name;

    public Student(int resId, String name) {
        this.resId = resId;
        this.name = name;
    }

    public int getResId() {
        return resId;
    }

    public void setResId(int resId) {
        this.resId = resId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

二、Item佈局檔案 student_item.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <import type="com.dfsebook.myrecycleradapter.bean.Student"/>
        <variable name="student" type="Student"/>
    </data>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center">

        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_margin="10dp"
            app:studentAvatar="@{student.resId}"/>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="40dp"
            android:gravity="center"
            android:text="@{student.name}"
            android:textSize="18sp" />

    </LinearLayout>
</layout>


三、自定義繫結行為 BindingUtil

package com.dfsebook.myrecycleradapter.utils;

import android.databinding.BindingAdapter;
import android.widget.ImageView;

/**
 * Created by Administrator on 16-7-18.
 */
public class BindingUtil {

    @BindingAdapter("bind:studentAvatar")
    public static void showImageByUrl(final ImageView imageView,int resId){
        imageView.setImageResource(resId);
    }
}

四、主佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</LinearLayout>

五、程式碼實現:MainActivity.java

package com.dfsebook.myrecycleradapter.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;

import com.dfsebook.myrecycleradapter.BR;
import com.dfsebook.myrecycleradapter.utils.InitRecyclerView;
import com.dfsebook.myrecycleradapter.R;
import com.dfsebook.myrecycleradapter.adapter.CommonAdapter;
import com.dfsebook.myrecycleradapter.bean.Student;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

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

        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.show_list);

        List<Student> students = new ArrayList<>();
        Student student = new Student(R.drawable.tx2,"Kate");
        students.add(student);
        student = new Student(R.drawable.tx3,"Kate");
        students.add(student);
        student = new Student(R.drawable.tx4,"Johnson");
        students.add(student);
        student = new Student(R.drawable.tx5,"Make");
        students.add(student);

        CommonAdapter<Student> adapter = new CommonAdapter<Student>(students,R.layout.student_item, BR.student);
        recyclerView.setAdapter(adapter);
    }
}
六、輔助工具類InitRecyclerView

package com.dfsebook.myrecycleradapter.utils;


import android.content.Context;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

/**
 * Created by Administrator on 15-9-17.
 */
public class InitRecyclerView {

    public static void initLinearLayoutVERTICAL(Context context,RecyclerView recyclerView){
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    public static void initLinearLayoutWithoutDivid(Context context,RecyclerView recyclerView){
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    public static void initLinearLayoutHorizontal(Context context,RecyclerView recyclerView){
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    public static void initStaggered(Context context,RecyclerView recyclerView){
        StaggeredGridLayoutManager sgm = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(sgm);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }
}


收工,執行截圖如下


相關文章