我正在尝试处理 Recycler View 中的触摸事件-:
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private ClickListener clickListener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if(child!=null && clickListener!=null)
{
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
Log.i("TAG", "Radhe handling LongPress ");
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if(child!=null && clickListener!=null && gestureDetector.onTouchEvent(e));
{
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener{
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
我还有以下代码-:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
filterAdapter = new FilterAdapter(getActivity(), getData());
recyclerView.setAdapter(filterAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
@Override
public void onClick(View view, int position) {
Log.i("TAG", "Radhe child Clicked ");
Toast.makeText(getActivity(),"CLick",Toast.LENGTH_SHORT).show();
}
@Override
public void onLongClick(View view, int position) {
Log.i("TAG", "Radhe child Long Clicked ");
Toast.makeText(getActivity(),"Long CLick",Toast.LENGTH_SHORT).show();
}
}));
return layout;
}
现在当我运行它时 -: 和
有人能告诉为什么会这样吗?我不知道这是什么原因。提前致谢。
最佳答案
我通常在 适配器 中处理点击事件,并通过如下界面与 fragment/Activity 交互。
在您的适配器的 onBindViewHolder 中;
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemClicked(holder.aValue);
}
});
而 mListener 是一个接口(interface)
public interface IclickListener<T> {
void onItemClicked(T object);
}
关于android - 在 Recyclerview 中多次调用 onClick,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34510215/