android - View.OnTouchListener() 不适用于父布局

标签 android android-layout android-listview android-linearlayout android-gesture

我在父布局上设置了一个 View.OnTouchListener,但它似乎不起作用。

这是 UI 的 XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="vertical"
    android:id="@+id/mainActivityLinearLayout"
    android:background="@drawable/listviewborder"
    tools:context=".MainActivity" >

    <View
        android:id="@+id/lineView"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="@color/gray" />

    <ListView
        android:id="@+id/gameListView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:dividerHeight="2dp" />

</LinearLayout>

这是在父布局上设置的 OnTouchListener:

mainActivityView = this.findViewById(R.id.mainActivityLinearLayout);
mainActivityView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            System.out.println("Touch test activity");
            return true;
        }
    });

onTouch() 永远不会被调用,字符串也永远不会打印。

并不是说我已经为 ListView 实现了 OnItemClick,我只是希望能够检测到整个布局上的触摸。

我也试过

gameListView = (ListView) findViewById(R.id.gameListView);
gameListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            System.out.println("Touch test list");
            return true;
        }
    });

虽然这也不起作用。

为什么父布局没有获得触摸事件?我怎样才能让它工作?

最佳答案

通过在 onTouch() 中返回 true,您消费了触摸事件;不会调用父 View 的 OnTouchListener。 The documentation states :

public abstract boolean onTouch (View v, MotionEvent event)

[...]

Returns
True if the listener has consumed the event, false otherwise.

您可能有兴趣让父 ViewGroup 通过 onInterceptTouchEvent() 拦截其子项的触摸事件,as detailed in this guide .

关于android - View.OnTouchListener() 不适用于父布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21247229/

相关文章:

android - Monkeyrunner 脚本不运行,但命令有效

android - 不断地为 Loading... textview 设置动画

android - 将 SurfaceView 与其他 View (如 TextView 和 Buttons)组合

android-更改某些行的自定义 ListView 背景

android - 为什么 android 插件 3.2.1 在缓存中使用 aapt2 而不是使用我的构建工具?

android - 添加 BulletSpan 时 EditText 不增加宽度

android - GridView 中网格的填充

java - 如何从数据库添加图像到 ListView 中?

java - 多选 ListView 和 SharedPreferences

android - 如何访问android库自己的资源