美文网首页
RecyclerView的使用(基于Data binding)

RecyclerView的使用(基于Data binding)

作者: 奔跑吧小马哥 | 来源:发表于2021-05-26 11:40 被阅读0次

    RecyclerView自带滑动效果,可以实现横向也可纵向,这点与listview不同。默认情况是纵向的,如果需要使用横向,需要通过setLayoutManager来进行设置。

    这篇文章记录了使用data binding来实现一个简单的RecyclerView的过程,其中包括两个布局文件要使用data binding,一个是包含RecyclerView的Activity的布局,另外一个是用于承载RecyclerView item的布局文件。

    下面看看使用RecyclerView的关键步骤:

    1. Activity布局
    <?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"
        xmlns:tools="http://schemas.android.com/tools">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <Button
                android:id="@+id/btn_trigger"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="刷新列表"/>
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/view_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </layout>
    
    1. RecyclerView 布局
      这个布局文件用于定义每条View需要显示的UI元素,这个demo显示的View从左到右要显示一个序号(TextView), 一个品牌名(TextView)
    <?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"
        xmlns:tools="http://schemas.android.com/tools">
        <data>
            <variable
                name="vm"
                type="com.mike.androidtips.recyclerViewDatabinding.DeviceModel" />
        </data>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="@{vm.rank}"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="40dp"
                android:text="@{vm.brand}"
                />
        </LinearLayout>
    </layout>
    
    1. 定义数据实体Model
    package com.mike.androidtips.recyclerViewDatabinding;
    import androidx.databinding.ObservableField;
    public class DeviceModel {
        public ObservableField<String> rank = new ObservableField();
        public ObservableField<String> brand = new ObservableField<>();
        public DeviceModel(DataEntity dataEntity) {
            this.rank.set(dataEntity.getRank());
            this.brand.set(dataEntity.getBrand());
        }
        public void setData(DataEntity dataEntity) {
            this.rank.set(dataEntity.getRank());
            this.brand.set(dataEntity.getBrand());
        }
    }
    

    DataEntity

    package com.mike.androidtips.recyclerViewDatabinding;
    
    public class DataEntity {
        String rank;
        String brand;
        public DataEntity(String rank, String brand) {
            this.rank = rank;
            this.brand = brand;
        }
        @Override
        public String toString() {
            return "DataEntity{" +
                    "rank='" + rank + '\'' +
                    ", brand='" + brand + '\'' +
                    '}';
        }
        public String getBrand() {
            return brand;
        }
        public String getRank() {
            return rank;
        }
    }
    
    1. 自定义一个RecyclerView的adapter,继承自RecyclerView.Adapter<RecyclerView.ViewHolder>并复写其关键方法,自定义的adapter里面需要去自定义一个ViewHolder,看下面代码:
    package com.mike.androidtips.recyclerViewDatabinding;
    
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import com.mike.androidtips.R;
    import com.mike.androidtips.databinding.RecyclerviewItemsBinding;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RecycleViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private final String TAG = RecycleViewAdapter.class.getSimpleName();
        List<DataEntity> dataEntities = new ArrayList<>();
        public void setDataEntities(List<DataEntity> entities) {
            dataEntities = entities;
        }
    
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
            return new MyViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            MyViewHolder myViewHolder = (MyViewHolder) holder;
            Log.d(TAG, "position = " + position + " , content: " + dataEntities.get(position));
            myViewHolder.binding.setVm(new DeviceModel(dataEntities.get(position)));
        }
    
        @Override
        public int getItemCount() {
            return dataEntities.size();
        }
    
        private class MyViewHolder extends RecyclerView.ViewHolder {
            public RecyclerviewItemsBinding binding;
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                binding = RecyclerviewItemsBinding.bind(itemView);
            }
        }
    }
    
    
    1. Activity里面的操作步骤:
      5.1 给RecyclerView 设置setLayoutManager
      5.2 实例化一个自定义adapter对象
      5.3 给adapter赋初始list
      5.4 把adapter设置给RecyclerView
    package com.mike.androidtips.recyclerViewDatabinding;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import androidx.databinding.DataBindingUtil;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import com.mike.androidtips.R;
    import com.mike.androidtips.databinding.ActivityRecyclerDatabindingBinding;
    import com.mike.androidtips.databinding.ActivityTestDatabindingBinding;
    import java.util.ArrayList;
    import java.util.List;
    
    public class RecyclerViewDataBindingActivity extends Activity {
        private final String TAG = RecyclerViewDataBindingActivity.class.getSimpleName();
    
        private RecycleViewAdapter adapter;
        ActivityRecyclerDatabindingBinding binding;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            binding = DataBindingUtil.setContentView(this, R.layout.activity_recycler_databinding);
            binding.viewRecyclerview.setLayoutManager(new LinearLayoutManager(this)); //默认是vertical
            //比如制作一个水平方向的水果列表,图标名字上下排列
            //binding.viewRecyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
            adapter = new RecycleViewAdapter();
            List<DataEntity> list = new ArrayList<>();
            DataEntity dataEntity = new DataEntity("1", "Apple");
            DataEntity dataEntity1 = new DataEntity("2", "Samsung");
            DataEntity dataEntity2 = new DataEntity("3", "OPPO");
            list.add(dataEntity);
            list.add(dataEntity1);
            list.add(dataEntity2);
            adapter.setDataEntities(list);
            binding.viewRecyclerview.setAdapter(adapter);
            initUI();
        }
    
        private void initUI() {
            binding.btnTrigger.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    List<DataEntity> list = new ArrayList<>();
                    DataEntity dataEntity = new DataEntity("1", "Samsung");
                    DataEntity dataEntity1 = new DataEntity("2", "chuanyin");
                    DataEntity dataEntity2 = new DataEntity("3", "chuizi");
                    DataEntity dataEntity3 = new DataEntity("4", "vivo");
                    list.add(dataEntity);
                    list.add(dataEntity1);
                    list.add(dataEntity2);
                    list.add(dataEntity3);
                    adapter.setDataEntities(list);
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }
    
    
    1. 运行结果


      result.png

    注:最初在调试时候遇到了问题:无论如何修改,整个list显示的都是最后一组数据
    原因:DeviceModel里的数据被定义成了static, 干掉static即解决了问题

        public static ObservableField<String> rank = new ObservableField();
        public static ObservableField<String> brand = new ObservableField<>();
    

    相关文章

      网友评论

          本文标题:RecyclerView的使用(基于Data binding)

          本文链接:https://www.haomeiwen.com/subject/xekksltx.html