RecyclerView dispatchTouchEvent 禁止滑动但是可以点击item 并且获取到点击item的数据 不要OnTouchListener
时间: 2024-03-16 12:44:35 浏览: 67
可以在 RecyclerView 的 Adapter 中重写 onBindViewHolder 方法,为每个 Item 添加一个点击事件监听器,然后在监听器中处理点击事件,并获取点击的数据。同时设置 RecyclerView 的 LayoutManager 为 LinearLayoutManager,并重写 canScrollVertically 方法返回 false,禁止 RecyclerView 滑动。示例代码如下:
```
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<MyData> mDataList;
private OnItemClickListener mItemClickListener;
public MyAdapter(List<MyData> dataList) {
mDataList = dataList;
}
public void setOnItemClickListener(OnItemClickListener listener) {
mItemClickListener = listener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final MyData data = mDataList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(data);
}
}
});
holder.bindData(data);
}
@Override
public int getItemCount() {
return mDataList.size();
}
}
public interface OnItemClickListener {
void onItemClick(MyData data);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
}
public void bindData(MyData data) {
mTextView.setText(data.getText());
}
}
public class MyData {
private String mText;
public MyData(String text) {
mText = text;
}
public String getText() {
return mText;
}
}
// 禁止 RecyclerView 滑动
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()) {
@Override
public boolean canScrollVertically() {
return false;
}
};
recyclerView.setLayoutManager(layoutManager);
// 处理点击事件并获取数据
MyAdapter adapter = new MyAdapter(dataList);
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(MyData data) {
// 处理点击事件并获取数据
}
});
recyclerView.setAdapter(adapter);
```
注意:这种方式只适用于禁止 RecyclerView 滑动但是可以点击 Item 并获取数据的情况,如果需要更复杂的交互,建议使用 OnTouchListener 处理事件。
阅读全文