欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android MVVM开发框架——(3)DataBinding 应用于RecyclerView

程序员文章站 2024-03-21 13:45:04
...

android MVVM开发框架——(1)DataBinding 基础应用

android MVVM开发框架——(2)DataBinding 应用于ListView

如果你对mvvm或者databinding不太熟悉的,建议先去看看前两篇博文

1,item布局沿用上一篇listview的布局,这里就不贴出来了

2,recyclervice布局

<?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.lh.mvvm.adapter.RecyclerViewAdapter" />

        <variable
            name="adapter"
            type="RecyclerViewAdapter" />
        <!--这里可以让modle可以控制recyclerview的背景色-->
        <variable
            name="image"
            type="int" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_test"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.1"
            android:background="@{image}"
            app:adapter="@{adapter}" />
    </LinearLayout>
</layout>

3,RecyclerViewHolder

public class RecyclerViewHolder extends RecyclerView.ViewHolder {

    //这里只要给RecyclerView.ViewHolder返回一个view就可以,所以我们将构造方法中传入databinding
    ItemMvvmBinding itemMvvmBinding;

    public RecyclerViewHolder(ItemMvvmBinding itemMvvmBinding) {
        super(itemMvvmBinding.getRoot());
        this.itemMvvmBinding = itemMvvmBinding;
    }

    public ItemMvvmBinding getBinding() {
        return itemMvvmBinding;
    }

    public void setBinding(ItemMvvmBinding itemMvvmBinding) {
        this.itemMvvmBinding = itemMvvmBinding;
    }
}

4,RecyclerViewAdapter

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> implements View.OnClickListener {
    private List<UserBean> data;
    /**
     * 用于模仿listview的itemclick事件,recyclerview没有itemclick
     */
    private OnItemClickListener mOnItemClickListener;


    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public RecyclerViewAdapter(List<UserBean> data) {
        this.data = data;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ItemMvvmBinding itemMvvmBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_mvvm, parent, false);
        itemMvvmBinding.getRoot().setOnClickListener(this);
        return new RecyclerViewHolder(itemMvvmBinding);
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        ItemMvvmBinding itemMvvmBinding = holder.getBinding();
        UserBean userBean = data.get(position);
        itemMvvmBinding.setUser(userBean);
        //将position保存在itemView的Tag中,以便点击时进行获取
        itemMvvmBinding.getRoot().setTag(position);
        itemMvvmBinding.btnUpdate.setOnClickListener(new OnBtnClickListener(1, userBean));
        itemMvvmBinding.btnDelete.setOnClickListener(new OnBtnClickListener(2, position));
        // 立刻执行绑定
        itemMvvmBinding.executePendingBindings();
    }

    private class OnBtnClickListener implements View.OnClickListener {
        private int stats;//1,修改;2,删除
        private UserBean userBean;
        private int position;

        OnBtnClickListener(int stats, UserBean userBean) {
            this.stats = stats;
            this.userBean = userBean;
        }

        OnBtnClickListener(int stats, int position) {
            this.stats = stats;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            switch (stats) {
                case 1:
                    userBean.userName.set("修改后的名字");
                    break;
                case 2:
                    data.remove(position);
                    notifyDataSetChanged();
                    break;
            }
        }
    }

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

    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null)
            mOnItemClickListener.onItemClick(v, (int) v.getTag());
    }
}

5,RecyclerViewActivity

public class RecyclerViewActivity extends Activity {

    ActivityRecyclerViewBinding recyclerViewBinding;
    ArrayList<UserBean> data;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recyclerViewBinding = DataBindingUtil.setContentView(this, R.layout.activity_recycler_view);
        data = initData();
        //需要设置recyclerview的layoutmanager,不然视图无法显示
        //第二个参数表示水平布局,第三个参数表示是否反转,视图从下往上滑
        //new GridLayoutManager(this,3,GridLayoutManager.HORIZONTAL,false)); //表格布局
        //new LinearLayoutManager(recyclerView.getContext(), LinearLayoutManager.VERTICAL, true));
        //new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));//瀑布流
        recyclerViewBinding.recyclerTest.setLayoutManager(new LinearLayoutManager(this, GridLayoutManager.VERTICAL, false));
        //初始化适配器
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(data);
        //绑定适配器
        recyclerViewBinding.setAdapter(recyclerViewAdapter);
        //item的点击事件
        recyclerViewAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(RecyclerViewActivity.this, "行数:" + position, Toast.LENGTH_LONG).show();
            }
        });
        //通过属性设置view的背景色
        recyclerViewBinding.setImage(getResources().getColor(R.color.colorAccent));
    }

    //初始化测试数据
    private ArrayList<UserBean> initData() {
        ArrayList<UserBean> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            UserBean userBean = new UserBean();
            userBean.userId.set(i);
            userBean.userName.set(i + "aaa");
            userBean.userAge.set(18 + i);
            userBean.userSex.set(i % 2 == 0 ? 1 : 0);
            list.add(userBean);
        }
        return list;
    }
}

recyclerview与databinding之间的绑定就是这样

Demo下载