My RecyclerVIew in Fragment
我的活动容器:
我的片段:
<android.support.design.widget.AppBarLayout>
<android.support.v7.widget.Toolbar/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?actionBarSize"
android:clipToPadding="false"
android:paddingBottom="8dp"
android:paddingLeft="8dp" />
我的CardView:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="2dp"
app:cardElevation="2dp">
...
</android.support.v7.widget.CardView>
OnClickListener:
holder.card.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Log.d("click","click");
}
});
为什么cardview无法点击?我做错了什么?
答案 0 :(得分:0)
RecyclerView与ListView有很大不同。这意味着必须以不同方式设置OnClickListener!我就是这样做的。
第1步 - 创建一个可以重复使用的类:
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
{
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
{
@Override
public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
@Override
public void onLongPress(MotionEvent e){
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null){
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
{
View childView = view.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
现在您已经拥有了这个类,您只需将Click监听器附加到Fragment或Activity中的RecyclerView,就像这样:
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView, new RecyclerItemClickListener
.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
//handle click events here
}
@Override
public void onItemLongClick(View view, int position) {
//handle longClick if any
}
}));
我希望这会对你有所帮助,因为我觉得这与CardView无关!祝你好运!