1. 程式人生 > >[Android]RecyclerView基本使用+adapter回撥介面實現點選事件

[Android]RecyclerView基本使用+adapter回撥介面實現點選事件

一、概述

RrcyclerView是ListView的加強版,不僅可以輕鬆實現和ListView同樣的效果,還優化了ListView中存在的各種不同之處。

Android官方推薦我們使用RecyclerView。

二、基本用法

1.首先需要在專案的build.gradle中新增相應的依賴庫:

implementation 'com.android.support:recyclerview-v7:27.1.1'

2.在layout佈局中新增RecyclerView空間:activity_list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<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/recycle_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

 3.新建Adapter介面卡:FruitRecyclerAdapter.java

public class FruitRecyclerAdapter extends RecyclerView.Adapter<FruitRecyclerAdapter.ViewHolder> {

    //資料來源
    private List<Fruit> mFruitList;

    public FruitRecyclerAdapter(List<Fruit> mFruitList) {
        this.mFruitList = mFruitList;
    }

    //自定義內部類 ViewHolder
    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView fruitImage;
        TextView fruitName;
        Button button;
        LinearLayout itemDetail;

        public ViewHolder(View itemView) {
            super(itemView);
            fruitImage = (ImageView) itemView.findViewById(R.id.fruit_image);
            fruitName = (TextView) itemView.findViewById(R.id.fruit_name);
            button = (Button) itemView.findViewById(R.id.fruit_button);
            itemDetail = (LinearLayout) itemView.findViewById(R.id.item_detail);
        }
    }

    //用於建立ViewHolder例項,並載入佈局
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    //對RecyclerView子項資料進行賦值
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

    //RecyclerView子項的個數
    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
}

4. 新建item子佈局layout:fruit_item.xml

  • 新建介面卡類要繼承RecyclerView.Adapter<...>,繼承的泛型ViewHolder需要我們自己新建內部類ViewHolder。
  • 內部類ViewHolder,繼承RecyclerView.ViewHolder。
  • 新建建構函式,初始化資料來源list。
  • 因為繼承了RecyclerView.Adapter,所以要重寫onCreateViewHolder()、onBindViewHolder()、getItemCount()三個方法。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_detail"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/border"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <Button
        android:id="@+id/fruit_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="點選" />

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="10dp" />


</LinearLayout>

 5.activity對RecyclerView的處理:

        recyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new FruitRecyclerAdapter(fruitList);
        recyclerView.setAdapter(adapter);

layoutmanager用於指定RecyclerView的佈局方式:

  • LinearLayoutManager.VERTICAL :線性垂直
  • LinearLayoutManager.HORIZONTAL:線性水平
  • GridLayoutManager.VERTICAL :網格垂直
  • GridLayoutManager.HORIZONTAL:網格水平
  • StaggeredGridLayoutManager.VERTICAL:瀑布流

 獲取adapter例項,並傳入資料來源list。最後呼叫RecyclerView的setAdapter()方法。

到此RecyclerView和資料之間的關聯就建立好了。


三、新增點選事件

大多數情況下,我們需要實現每個item本身或者item中的button等控制元件的點選事件。就需要在adapter中用到介面回撥,

添加了介面回撥的adapter程式碼如下:

public class FruitRecyclerAdapter extends RecyclerView.Adapter<FruitRecyclerAdapter.ViewHolder> {

    //資料來源
    private List<Fruit> mFruitList;
    //介面
    private ClickInterface clickInterface;

    public FruitRecyclerAdapter(List<Fruit> mFruitList) {
        this.mFruitList = mFruitList;
    }

    //--------------------點選事件-------------------------------------------//
    public void setOnclick(ClickInterface clickInterface) {
        this.clickInterface = clickInterface;
    }

    //回撥介面
    public interface ClickInterface {
        void onButtonClick(View view, int position);

        void onItemClick(View view, int position);
    }
    //--------------------點選事件-------------------------------------------//

    //自定義內部類 ViewHolder
    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView fruitImage;
        TextView fruitName;
        Button button;
        LinearLayout itemDetail;

        public ViewHolder(View itemView) {
            super(itemView);
            fruitImage = (ImageView) itemView.findViewById(R.id.fruit_image);
            fruitName = (TextView) itemView.findViewById(R.id.fruit_name);
            button = (Button) itemView.findViewById(R.id.fruit_button);
            itemDetail = (LinearLayout) itemView.findViewById(R.id.item_detail);
        }
    }

    //用於建立ViewHolder例項,並載入佈局
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    //對RecyclerView子項資料進行賦值
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());

        //--------------------點選事件-------------------------------------------//
        //Button點選事件
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickInterface != null) {
                    clickInterface.onButtonClick(v, position);
                }
            }
        });
        //item點選事件
        holder.itemDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickInterface != null) {
                    clickInterface.onItemClick(v, position);
                }
            }
        });
        //--------------------點選事件-------------------------------------------//
    }

    //RecyclerView子項的個數
    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
}

 Activity程式碼中的點選事件處理:

        recyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new FruitRecyclerAdapter(fruitList);
        recyclerView.setAdapter(adapter);

        //新增點選事件
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                adapter.setOnclick(new FruitRecyclerAdapter.ClickInterface() {
                    @Override
                    public void onButtonClick(View view, int position) {
                        Toast.makeText(view.getContext(), "Click Button - position: " + position + "   name: " + fruitList.get(position).getName(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onItemClick(View view, int position) {
                        Toast.makeText(view.getContext(), "Click Item Detail - position: " + position + "   name: " + fruitList.get(position).getName(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

這裡實現了item和button的兩個點選事件。


END.