Android:设置为可点击的块onTouch事件时的RecyclerView项

Ilj*_* S. 8 android android-recyclerview

看起来像将RecyclerView的项目布局设置为clickable ="true",完全消耗一些触摸事件,特别是MotionEvent.ACTION_DOWN(事后ACTION_MOVE和ACTION_UP正在工作):

item.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/demo_item_container"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"> <-- this what breaks touch event ACTION_DOWN

....    
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在onCreate()中具有非常基本的RecyclerView设置:

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);    
... //Standard recyclerView init stuff

//Please note that this is NOT recyclerView.addOnItemTouchListener()
recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.d("", "TOUCH ---  " + motionEvent.getActionMasked());
                //Will never get here ACTION_DOWN when item set to android:clickable="true" 
                return false;
            }
      });
Run Code Online (Sandbox Code Playgroud)

这是在RecyclerView中的预期行为或错误导致它仍然是一个预览?

PS.我希望这可以按照文档进行点击,以对按下状态做出反应并对点击产生连锁反应.设置为false时ACTION_DOWN正常工作但未触发按下状态且selectableBackground没有任何效果.

小智 0

这是预期行为而不是错误。

当设置item clickable true时,ACTION_DOWN将被消耗,回收器视图将永远不会获得ACTION_DOWN。

为什么回收器视图的 onTouch() 中需要 ACTION_DOWN ?有必要吗?如果你想在ACTION_DOWN中设置lastY,为什么不这样做

    case MotionEvent.ACTION_MOVE:
        if (linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
        // initial
        if (lastY == -1)
            lastY = y;

        float dy = y - lastY;
        // use dy to do your work

        lastY = y;
        break;
    case:MotionEvent.ACTION_UP:
        // reset
        lastY = -1;
        break;
Run Code Online (Sandbox Code Playgroud)

你愿意吗?如果您仍然想要 ACTION_DOWN,请尝试使其处于活动状态,例如:

 public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN)
    lastY = ev.getRawY();
    return super.dispatchTouchEvent(ev);
Run Code Online (Sandbox Code Playgroud)