android RecyclerView的简单使用实例

介绍

RecyclerView循环视图在应用中可以运用成列表视图、网格试图、瀑布流视图等,基本上一个RecyclerView+Adapter就无敌了。
ListView的缺点是不能设置单独的点击事件,RecyclerView可以定制点击事件这是最大的优点,以及强大的可扩展性是RecyclerView被广泛使用的原因。

使用

依赖注入、页面activity、子项的xml布局、页面xml、RecyclerView.Adapter适配器、数据源。
适配器必须重写的方法是
getItemCount获取列表项数量
onCreateViewHolder创建视图持有者
onBindViewHolder绑定试图持有者
其他具体使用可以看下面的具体代码或者查看官方文档

效果

瀑布流布局
android RecyclerView的简单使用实例_第1张图片
线性布局

android RecyclerView的简单使用实例_第2张图片
网格布局
android RecyclerView的简单使用实例_第3张图片
代码里的图片资源
android RecyclerView的简单使用实例_第4张图片

具体代码

导入依赖

implementation 'com.google.android.material:material:1.1.0'

创建页面activity和页面xml
activity

public class RecyclerViewActivity extends AppCompatActivity implements View.OnClickListener {
    private ArrayList<GoodsInfo> arrayList;
    RecyclerAdapter adapter;
    private RecyclerView recyclerView;
    private Button btn_add;
    String TAG = "RecyclerViewActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);
        recyclerView = findViewById(R.id.rv_cyc);
        btn_add = findViewById(R.id.btn_add);//按钮
        btn_add.setOnClickListener(this);//按钮监听
        //布局管理器
        GridLayoutManager manager = new GridLayoutManager(this, 2);//网格布局
        // StaggeredGridLayoutManager manager=new StaggeredGridLayoutManager(3, LinearLayout.VERTICAL);//瀑布流布局
        //LinearLayoutManager manager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);//线性布局
        recyclerView.setLayoutManager(manager);
        arrayList = GoodsInfo.getDefaultList();
        adapter = new RecyclerAdapter(this, arrayList);
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_add) {
            int position = (int) (Math.random() * 100 % arrayList.size());
            Log.d(TAG, "onClick: 测试" + position);
            GoodsInfo old_item = arrayList.get(position);
            GoodsInfo new_item = new GoodsInfo(old_item.img_id, old_item.text);
            arrayList.add(0, new_item);
            adapter.notifyItemInserted(0);
            recyclerView.scrollToPosition(0);

        }
    }


}

xml采用的是约束布局,点击按钮在recyclerview第一项添加一条

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".RecyclerViewActivity">

    <Button
        android:id="@+id/btn_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加一条"
        app:layout_constraintBottom_toTopOf="@+id/rv_cyc"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_cyc"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_add" />
</androidx.constraintlayout.widget.ConstraintLayout>

子项xml布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_recycler"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_img"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="13sp" />


</LinearLayout>

数据源


/**
 * @作者 chen
 * @时间 2020/4/21 16:02
 * @用途 模拟数据
 **/
public class GoodsInfo {

    public int img_id;
    public String text;
    public boolean bPressed;
    public int id;
    private static int seq = 0;

    public GoodsInfo(int img_id, String text) {
        this.img_id = img_id;
        this.text = text;
        this.bPressed = false;
        this.id = this.seq;
        this.seq++;
    }

    private static int[] listImageArray = {R.drawable.tt, R.drawable.tt
            , R.drawable.tt, R.drawable.tt, R.drawable.tt};
    private static String[] listTextArray = {"RecyclerView", "好好学习", "天天向上", "热爱祖国,热爱家乡", "为人民服务"};

    public static ArrayList<GoodsInfo> getDefaultList() {
        ArrayList<GoodsInfo> listArray = new ArrayList<GoodsInfo>();
        for (int i = 0; i < listImageArray.length; i++) {
            listArray.add(new GoodsInfo(listImageArray[i], listTextArray[i]));
        }
        return listArray;
    }

}

最后上适配器的代码

/**
 * @作者 chen
 * @时间 2020/4/21 15:55
 * @用途 recycler适配器
 **/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private ArrayList<GoodsInfo> arrayList;

    public RecyclerAdapter(Context context, ArrayList<GoodsInfo> arrayList) {
        this.context = context;
        this.arrayList = arrayList;

    }

    //创建视图持有者
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_recycler, parent, false);
        return new ItemHolder(v);
    }

    //绑定视图持有者
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        ItemHolder itemHolder = (ItemHolder) holder;
        itemHolder.iv_img.setImageResource(arrayList.get(position).img_id);
        itemHolder.text.setText(arrayList.get(position).text);

        //文本点击事件
        itemHolder.text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "第" + position + "项", Toast.LENGTH_SHORT).show();
            }
        });

        //图片长按事件,长按删除
        itemHolder.iv_img.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                GoodsInfo item = arrayList.get(position);
                item.bPressed = !item.bPressed;
                arrayList.set(position, item);
                Toast.makeText(context, "已删除", Toast.LENGTH_SHORT).show();
                arrayList.remove(position);
                notifyItemRemoved(position);
                return true;
            }
        });

    }

    //列表个数
    @Override
    public int getItemCount() {
        return arrayList.size();
    }


    //定义视图持有者
    public class ItemHolder extends RecyclerView.ViewHolder {
        private ImageView iv_img;
        private TextView text;

        public ItemHolder(@NonNull View itemView) {
            super(itemView);
            iv_img = itemView.findViewById(R.id.iv_img);
            text = itemView.findViewById(R.id.tv_text);
        }
    }

}

你可能感兴趣的:(android RecyclerView的简单使用实例)