gpt4 book ai didi

java - 单击回收器 View

转载 作者:行者123 更新时间:2023-12-01 17:54:50 25 4
gpt4 key购买 nike

使用RecyclerView的人是否找到了为RecyclerView中的项目设置onClickListener的方法?我想过为每个项目的每个布局设置一个监听器,但这似乎有点太麻烦了我确信有一种方法可以让 RecyclerView 监听 onClick 事件,但我不太明白。

最佳答案

这里有一种更好且耦合性较低的方法来为 RecyclerView 实现 OnClickListener

使用 fragment :

RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, recyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
// do whatever
}

@Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);

RecyclerItemClickListener 实现:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;


public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;

public interface OnItemClickListener {
public void onItemClick(View view, int position);

public void onLongItemClick(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 child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}

@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 true;
}
return false;
}

@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }

@Override
public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}

关于java - 单击回收器 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com