我开始在Android中使用RecyclerView。在我为我的适配器实现触摸侦听器之前,工作正常。
从这个主题:
https://stackoverflow.com/a/26826692/2923403
我可以正确实现childview的监听器。但是,我想实现OnItemClick和OnItemLongClick,然后出现问题。他们总是同时被解雇。 OnItemClick首先和OnItemLongClick稍后,这使我的函数无用。
以下是自定义侦听器的代码(基于上面的代码,感谢Fouad):
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public static interface OnItemClickListener {
public boolean onItemClick(View view, int position);
public void onItemLongClick(View view, int position);
}
GestureDetector mGestureDetector;
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.getChildPosition(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.getChildPosition(childView));
return true;
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
对于实施:
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public boolean onItemClick(View view, int position) {
//This is fired 1st
}
@Override
public void onItemLongClick(View view, int position) {
//This comes later
}));
你有解决方法吗?
答案 0 :(得分:35)
您可以在自定义适配器实现中添加侦听器。它将类似于:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
public interface OnItemClickListener {
public void onItemClicked(int position);
}
public interface OnItemLongClickListener {
public boolean onItemLongClicked(int position);
}
private Fragment mFragment;
public static class ViewHolder extends RecyclerView.ViewHolder {
public View v;
public ViewHolder(View v) {
super(v);
this.v = v;
}
}
public RecyclerViewAdapter(Fragment fragment) {
mFragment = fragment;
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mFragment.onItemClicked(position);
}
});
holder.v.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mFragment.onItemLongClicked(position);
return true;
}
});
}
. . .
}
注意开头的接口定义。这样,您就可以将onClick和onLongClick事件传递给您的片段进行处理。非常方便,你知道吗