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>
效果图如下:
点击效果
网友评论