1 回答

TA貢獻1815條經驗 獲得超13個贊
嘗試這個:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<Button
android:id="@+id/btnTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Android xml 視圖的創建方式類似于堆棧,其中 xml 文件中較低的視圖呈現在文件中較早的視圖之上。
聽起來您的線性布局正在攔截觸摸事件,防止它們傳播到其下方的按鈕。
檢查這一點的方法是在線性布局上設置背景,您會看到當它具有彩色背景時按鈕不可見。
更新:
由于需要允許按鈕和布局的觸摸事件,我將擴展我的解決方案。
OnClickListeners 是在 Android 視圖上接收點擊事件的標準方法。然而,在下面有OnTouchListeners,它們處理視圖上的原始觸摸而不是單擊事件。
當以任何方式觸摸 Android 屏幕時,都會記錄事件,并且 Android 會將觸摸事件發送到觸摸事件遇到的第一個視圖。OnTouchListeners 返回一個布爾值,指示它們是否消耗了該事件。如果它們沒有消耗該事件,則該事件將傳播到觸摸事件將遇到的層次結構中的下一個視圖。
這就是為什么您的單擊按鈕最初從未被注冊,因為布局正在消耗觸摸事件并阻止其傳播到按鈕。
這是標準的 Android 行為,只有一個視圖可以處理任何單個觸摸事件。
決定采取其他措施表明您應該考慮應用程序的設計并決定這種行為是否絕對必要。
但是,如果您的情況是罕見的情況之一,我將提供觸摸監聽器的示例。
請注意,這個觸摸監聽器假設您正在使用我上面發布的 xml 以及附加到原始問題中的按鈕的點擊監聽器。
getActivity()
.findViewById(R.id.parentLayout)
.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e(TAG, "onTouch: ");
return false;
}
});
然而,這將在用戶觸摸布局時觸發,并在用戶釋放時再次觸發,因為這是兩個單獨的運動事件。
要僅觸發一種類型的運動事件,您需要檢查傳遞的事件。
getActivity()
.findViewById(R.id.parentLayout)
.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.e(TAG, "onTouch: ");
}
return false;
}
});
在此代碼中,僅當用戶從視圖中抬起手指時才會發生日志,因為ACTION_UP是用戶抬起手指的事件操作。
添加回答
舉報