Android 用Databinding写recyclerview的adapter

来源:互联网 发布:免费弱视训练软件 编辑:程序博客网 时间:2024/06/06 09:56

Android 用Databinding写recyclerview的adapter

1还是写一个模板,以后要用的时候直接cv大法,粘贴自己写的模板毕竟更方便。

2随便来一个item的布局

<?xml version="1.0" encoding="utf-8"?><layout>    <data>        <variable            name="listBean"            type="com.fargister.run.pic.first.bean.PicNaviBean.ShowapiResBodyBean.ListBeanX.ListBean" />    </data>    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"        android:layout_width="match_parent"        android:layout_height="100px"        android:orientation="vertical">        <TextView            android:id="@+id/name"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_marginBottom="@dimen/px10"            android:layout_marginLeft="@dimen/px50"            android:layout_marginRight="@dimen/px50"            android:layout_marginTop="@dimen/px10"            android:background="@color/colorAccent"            android:text="@{listBean.name}" />    </LinearLayout></layout>

3与之对应的adapter

public class FirstNaviAdapter extends RecyclerView.Adapter<FirstNaviAdapter.ViewHolder> {    private List<PicNaviBean.ShowapiResBodyBean.ListBeanX.ListBean> listBeen;    private Context context;    public FirstNaviAdapter(List<PicNaviBean.ShowapiResBodyBean.ListBeanX.ListBean> listBeen, Context context) {//构造函数要数据跟上下文        this.listBeen = listBeen;        this.context = context;    }    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        ItemFirstNaviBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_first_navi,                parent, false);        return new ViewHolder(binding.getRoot());    }    @Override    public void onBindViewHolder(ViewHolder holder, int position) {        ItemFirstNaviBinding binding = DataBindingUtil.getBinding(holder.itemView);        binding.setListBean(listBeen.get(position));        binding.executePendingBindings();    }    @Override    public int getItemCount() {        return listBeen.size();    }    public static class ViewHolder extends RecyclerView.ViewHolder {        public ViewHolder(View itemView) {            super(itemView);        }    }}

代码很简单,没有什么要标记的

我之前还看过一个更优雅的写法,忘记了,等我有时间在学习一下在修改一下。