【问题标题】:Android: RecyclerView item when set to clickable blocks onTouch eventsAndroid:设置为可点击块时的 RecyclerView 项目 onTouch 事件
【发布时间】:2014-08-29 14:43:37
【问题描述】:

似乎将 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>

在 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;
            }
      });

这是 RecyclerView 中的预期行为或错误,因为它仍然是预览版吗?

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

【问题讨论】:

  • 尝试设置 android:focusable="true" ,我没有测试过这个,这就是为什么我没有提供它作为答案,但 ACTION_DOWN 对我来说似乎是一个焦点相关的事件。
  • @Iija,你有什么解决办法吗?我被同样的问题困扰了好几天了。
  • @Manu,我最终认为这是预期的行为。你应该能够通过使用 recyclerView.addOnItemTouchListener() 来实现你想要的......

标签: android android-recyclerview


【解决方案1】:

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

当设置item clickable为true时,会消耗ACTION_DOWN,recycler view 永远不会得到 ACTION_DOWN。

为什么在recycler view的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;

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

 public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN)
    lastY = ev.getRawY();
    return super.dispatchTouchEvent(ev);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多