为RecyclerView添加item的点击事件(个人备忘录)

本文摘录了http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0327/2647.html

一、前言

在上一篇博文中,我们介绍了RecyclerView的基本使用方式,以及贴出了核心代码。如果你亲手实践过的话,会发现,RecyclerView不像ListView一样提供item的点击监听,所以我们只能自己实现。RecyclerView的item点击事件监听可以为item的view设置监听,也可以在RecyclerView.addOnItemTouchListener里去判断手势来实现。这里,主要介绍为item的view设置监听。

二、目的

模拟ListView的setOnItemClickListener()方法,调用者只须调用类似于setOnItemClickListener的东西就能获得被点击item的相关数据。

三、原理

为RecyclerView的每个子item设置setOnClickListener,然后在onClick中再调用一次对外封装的接口,将这个事件传递给外面的调用者。而“为RecyclerView的每个子item设置setOnClickListener”在Adapter中设置。其实直接在onClick中也能完全处理item的点击事件,但是这样会破坏代码的逻辑。

四、步骤

adapter中

自定义一个继承自RecyclerView.Adapter的NotesAdapter。

1.在NotesAdapter中定义如下接口,模拟ListView的OnItemClickListener:

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

声明一个这个接口的变量

   private OnItemClickListener mOnItemClickListener;

在onCreateViewHolder()中为每个item添加点击事件

  @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_notes, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setOnClickListener(this);
        return viewHolder;
    }

将点击事件转移给外面的调用者:

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

注意上面调用接口的onItemClick()中的v.getTag()方法,这需要在onBindViewHolder()方法中设置和item的position

  @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Notes notes = mList.get(position);
        holder.notesContent.setText(notes.getContent());
        holder.itemView.setTag(position);
    }

最后暴露给外面的调用者,定义一个设置Listener的方法():

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

完整的NotesAdapter代码如下:

package com.linbots.simplenotes.ui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.linbots.simplenotes.R;
import com.linbots.simplenotes.db.Notes;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by LinBots on 2017/4/24.
 */

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.ViewHolder> implements View.OnClickListener {


    private Context context;
    private List mList;

    public NotesAdapter(Context context, List mList) {
        this.context = context;
        this.mList = mList;
    }


    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.notes_content)
        TextView notesContent;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_notes, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setOnClickListener(this);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Notes notes = mList.get(position);
        holder.notesContent.setText(notes.getContent());
        holder.itemView.setTag(position);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }


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

    private OnItemClickListener mOnItemClickListener;

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


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

}

在Activity中使用:

    @Override
    public void showNote(final List notes) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new NotesAdapter(this, notes);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new NotesAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                SToast(notes.get(position) + "");
            }
        });
    }

五、为RecyclerView增加点击效果:

新建新建drawable/recycler_item_selector.xml:


<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/color_bfbfbf" android:state_pressed="true"/>
    <item android:drawable="@color/color_bfbfbf" android:state_focused="true"/>
    <item android:drawable="@color/write"/>
selector>

注意,波纹效果只在5.0以上的设备生效

所以我们需要新建drawable-v21/recycler_item_selector.xml:


<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/color_bfbfbf">
    <item android:drawable="@color/write" />
ripple>

然后在item_notes.xml中设置android:background="@drawable/recycler_item_selector",完整代码如下:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:background="@drawable/recycler_item_selector"
    android:orientation="vertical">

    <TextView
        android:id="@+id/notes_content"
        android:layout_width="match_parent"
        android:layout_height="54.5dp"
        android:ellipsize="end"
        android:gravity="center_vertical"
        android:paddingLeft="16sp"
        android:singleLine="true"
        android:text="hello lanbots"
        android:textColor="#333333"
        android:textSize="15sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginLeft="16dp"
        android:background="#dedede" />
LinearLayout>

六、总结

在ListView中我们是调用ListView的setOnItemClickListener:

    mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {

                    ...           

            }
        });

而在我们这里是调用mAdapter的setOnItemClickListener。

七、实现效果

你可能感兴趣的:(android)