RecyclerView-->點選和長按事件

weixin_34249678發表於2018-10-12
1775338-c664a8bb3db77112.jpg

RecyclerView不像ListView提供了點選和長按的監聽事件,我們需要自己在Adaper中定義,如下所示:

public class TestAdapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    
    private OnItemClickListener mItemClickListener;
    private OnLongClickListener mLongClickListener;

    public void setItemClickListener(OnItemClickListener itemClickListener) {
        mItemClickListener = itemClickListener;
    }

    public void setLongClickListener(OnLongClickListener longClickListener) {
        mLongClickListener = longClickListener;
    }

    public interface OnItemClickListener{
        void onItemClick(int position);
    }
    
    public interface OnLongClickListener{
        boolean onLongClick(int position);
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) {
        //設定點選和長按事件
        if (mItemClickListener != null){
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mItemClickListener.onItemClick(i);
                }
            });
        }
        if (mLongClickListener != null){
            viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    return mLongClickListener.onLongClick(i);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return 0;
    }
}

RecyclerView的條目也沒有點選效果,我們可以通過以下方式實現;
在drawable和drawable-v21目錄下定義下面selector_recycler_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/color_click" android:state_pressed="true"/>
    <item android:drawable="@color/color_click" android:state_focused="true"/>
    <item android:drawable="@color/color_white"/>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/color_click">

    <item android:drawable="@color/color_white"/>

</ripple>

在條目中使用:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:gravity="center"
    android:id="@+id/tv_text"
    android:background="@drawable/selector_recycler_item"
    android:textSize="18sp"
    android:layout_height="50dp">

</TextView>

效果圖如下:

1775338-5a66253660a53dcd.gif
點選效果

相關文章