RecyclerView的OnItemClick在它的孩子的OnClick之前触发

时间:2017-03-12 05:04:22

标签: java android android-recyclerview imageview onclicklistener

我的学校项目遇到了一些问题。当我点击其内部的ImageButton时,我的RecyclerView OnItemClick被触发。

CODE

mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
  @Override
  public void onItemClick(View view, int position) {
    viewComments(posts.get(position));
  }

  @Override
  public void onItemLongClick(View view, int position) {

  }
}));

这里是RecyclerItemClickListener代码:

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

  private OnItemClickListener mListener;
  private GestureDetector mGestureDetector;

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

    void onItemLongClick(View view, int position);
  }

  public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
    mListener = listener;

    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
      @Override
      public boolean onSingleTapUp(MotionEvent e) {
        View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

        if (childView.findViewById(R.id.btnRateUp).isPressed() || childView.findViewById(R.id.btnRateDown).isPressed()) {
          return false;
        }

        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.getChildAdapterPosition(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.getChildAdapterPosition(childView));
    }

    return false;
  }

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

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

这是我想出的,以检测孩子是否获得了点击,

if(childView.findViewById(R.id.btnRateUp).isPressed() || childView.findViewById(R.id.btnRateDown).isPressed())

但我已经意识到方法isPressed()需要比RecyclerView OnItemClick处理更长的时间。该代码仅在我不快速点击时才有效。

btnRateUp和btnRateDown是ImageButtons,他们的OnClick事件正在适配器onBindViewHolder中实现,如下所示:

holder.getBtnRateUp().setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    doStuff(true);
  }
});

holder.getBtnRateDown().setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    doStuff(false);
  }
});

1 个答案:

答案 0 :(得分:0)

我通过改变完全完成它的方式解决了这个问题。遵循this教程。