我在父布局上设置了一个 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/