Android:使用触摸框架处理回收器视图项内的图像视图的点击
作者:互联网
我试图捕获包含在RecyclerView项目内的ImageView的点击.我已经实现了RecyclerView.OnItemTouchListener并且手势检测器处理正常点击的动作事件并长按RecyclerView项目.
由于我想要在RecylcerView项目中的子视图上使用相同的触摸框架处理触摸事件,我也将View.OnTouchListener设置为图像视图,覆盖onTouch实现,返回true,希望ImageView可以使用触摸当它被点击时.
我故意在来自RecyclerView的onInterceptTouchEvent中返回false,希望子视图首先处理事件,如果没有消耗,则RecyclerView的项视图将处理onTouchEvent处理期间点击的手势事件.
通过上述理解,我可以在单击它时在ImageView上接收触摸事件.
问题是,当我点击ImageView外部的RecyclerView项时,RecyclerView的onTouchEvent根本没有被调用.我对触摸框架的理解是,如果子视图不处理触摸事件,则RecyclerView的onTouchEvent应该有机会处理相同的事件.然而,这不是我能够实现的.
任何人都可以建议背后发生的事情以及处理上述点击事件的正确方法是什么?
解决方法:
这将解决您的问题:
public class OnItemClickListener implements View.OnClickListener {
private int position;
private OnItemClickCallback onItemClickCallback;
public OnItemClickListener(int position, OnItemClickCallback onItemClickCallback) {
this.position = position;
this.onItemClickCallback = onItemClickCallback;
}
@Override
public void onClick(View view) {
onItemClickCallback.onItemClicked(view, position);
}
public interface OnItemClickCallback {
void onItemClicked(View view, int position);
}
}
获取’OnItemClickCallback’接口的实例并将其放入您的活动或片段中:
private OnItemClickListener.OnItemClickCallback onItemClickCallback = new OnItemClickListener.OnItemClickCallback() {
@Override
public void onItemClicked(View view, int position) {
// switch(view.getId()) ...
}
};
然后,将该回调传递给recyclerView:
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(Arrays.asList("1", "2", "3"), onItemClickCallback));
最后,这将是你的适配器:
public class SimpleStringRecyclerViewAdapter extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
private List<String> mValues;
private OnItemClickListener.OnItemClickCallback onItemClickCallback;
public SimpleStringRecyclerViewAdapter(List<String> items, OnItemClickListener.OnItemClickCallback onItemClickCallback) {
mValues = items;
this.onItemClickCallback = onItemClickCallback;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mTextView;
public ViewHolder(View view) {
super(view);
mView = view;
mTextView = (TextView) view.findViewById(R.id.txt_title);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mTextView.setText(mValues.get(position));
holder.mView.setOnClickListener(new OnItemClickListener(position, onItemClickCallback));
holder.mTextView.setOnClickListener(new OnItemClickListener(position, onItemClickCallback));
}
@Override
public int getItemCount() {
return mValues.size();
}
}
标签:android,android-recyclerview,imageview,touch-event,ontouch 来源: https://codeday.me/bug/20191007/1864539.html