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

解決 ListView 中 Button 搶走點擊事件的問題

編輯:關於 Android 程式設計

在 ListView 的項目(item)裡嵌套 Button 時,常會遇到一個惱人的狀況:Button 把整行的點擊事件「吃掉了」,導致 item 本身的點擊監聽無法觸發。這是因為 Button 預設是可取得焦點(focusable)的,會攔截觸摸事件。

解法:調整焦點與事件分發

解決方式其實只需兩個屬性:

1. 在 item 佈局的根佈局上加上:
android:descendantFocusability="blocksDescendants"
這會阻擋子控制項取得焦點。
2. 在Button 上加上:
android:focusable="false"
讓按鈕不再搶走焦點。

兩處設定搭配使用後,item 與 Button 就都能各自正常點擊了。

佈局範例

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:descendantFocusability="blocksDescendants">

    <Button
        android:id="@+id/worklog_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改"
        android:focusable="false" />

    <Button
        android:id="@+id/worklog_del"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="刪除"
        android:focusable="false" />

</LinearLayout>

透過這兩個屬性的組合,就能兼顧「整行可點擊」與「行內按鈕可獨立點擊」這兩個需求。若使用 RecyclerView,思路類似,也可以在 item 根佈局套用 descendantFocusability,或於 Adapter 中妥善處理事件分發。

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