我正在開發一個Android
應用程序,我試圖在我的整個屏幕中捕獲OnTouch
events
。我的所有activities
都會有一個標題,其中包含兩個buttons
,然後是一個正在改變的主體。在屏幕的頂部Android:onTouchListener在根視圖(RelativeLayout)不起作用
- 兩個Buttons
:
在Activity
,我現在測試的身體是一個ListView
,所以Activity
了。
- ListView
這兩個按鈕下。
我想在整個屏幕中捕獲onTouchEvents
。我嘗試將OnTouchListener
設置爲我的根RelativeLayout
,並將clickable = false和focusable = false設置爲所有其他視圖,但它不起作用:onTouch事件僅在單擊第一個按鈕時觸發。
這是我的佈局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
tools:context=".MainActivity" >
<include
layout="@layout/header"
android:clickable="false"
android:focusable="false" />
<ListView
android:id="@+id/lvLocations"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/header_layout"
android:clickable="false"
android:focusable="false" />
</RelativeLayout>
這是@佈局/頭的內容:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:weightSum="5" >
<Button
android:id="@+id/homeButton"
android:layout_width="0dip"
android:layout_height="50dp"
android:layout_marginRight="5dp"
android:layout_weight="4"
android:clickable="false"
android:focusable="false"
android:onClick="Home"
android:text="@string/home" />
<ImageButton
android:id="@+id/speechButton"
android:layout_width="0dip"
android:layout_height="50dp"
android:layout_weight="1"
android:clickable="false"
android:focusable="false"
android:onClick="ClickMediaButton"
android:src="@drawable/micro" />
</LinearLayout>
這是我使用的代碼:
findViewById(R.id.root).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("MACT", "TOUCH!");
}
});
就像我說的,我的日誌只有當homeButton被點擊時才顯示TOUCH 。這是爲什麼?我究竟做錯了什麼?
謝謝!
有趣。我認爲發生的事情是,因爲有多個視圖捕捉觸摸 - 例如列表視圖,標題,按鈕 - 無法推薦,即使你想要的方式。我敢打賭,如果您製作了自定義視圖,在它們被任何視圖抓住之前抓住了觸摸,然後使用了導演類型模式來確定在更復雜的佈局下會發生什麼情況。在將視圖或網格放入視圖頁面之前,我曾遇到過類似的問題。只是一個想法。 – Rarw
真正有趣的評論,我從來沒有去過多的自定義視圖,所以我沒有想到這一點。看起來像一個不錯的方法:) –