Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

手機衛士實戰:Android 事件傳遞與響應規則解析

編輯:關於 Android 開發

搞懂 Android 事件傳遞與響應規則

在自定義 SettingItemView 的過程中,我們可能會遇到一個典型問題:點擊條目時 TextView 文字會改變,但直接點擊內部的 CheckBox 時,文字卻沒有反應。這背後其實牽涉到 Android 的事件傳遞機制。

問題的根源

SettingActivity 對應布局的根布局會先獲取點擊事件,然後將事件向下傳遞給 SettingItemView:

1. 點擊落在 SettingItemView 的非 CheckBox 區域時,事件由 SettingItemView 自己響應;
2. 點擊落在 CheckBox 區域時,事件會繼續傳遞給 CheckBox,由 CheckBox 響應。

一旦 CheckBox 響應了點擊事件,SettingItemView 就無法再響應,也就不會調用 onClick 去改變狀態,於是出現了文字不變的現象。

解決方案:讓 CheckBox 不響應點擊事件

思路很簡單——既然問題出在 CheckBox 搶走了事件,那就讓它不接收點擊即可。只需在布局中為 CheckBox 關閉可點擊與可獲焦屬性:

<!-- android:clickable="false" android:focusable="false" android:focusableInTouchMode="false" -->
<!-- 讓當前的 CheckBox 不能被點擊,即不能響應事件 -->
<CheckBox
 android:id="@+id/cb_box"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentRight="true"
 android:layout_centerVertical="true"
 android:clickable="false"
 android:focusable="false"
 android:focusableInTouchMode="false" />

這樣設置後,無論點擊條目的哪個區域,事件都會統一交由 SettingItemView 處理,狀態切換與文字更新便能保持一致。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved