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

Android 開發常見的 Lint 報錯與排查技巧

編輯:關於 Android 程式設計

在 Android 開發過程中,Lint 檢查經常會跳出一些看似不起眼、卻容易讓新手卡關的提示。以下整理幾個最常見的狀況,並附上對應的解法。

一、缺少 contentDescription 屬性

報錯訊息:[Accessibility] Missing contentDescription attribute on image

Lint 說明:像 ImageView、ImageButton 這類沒有文字內容的元件,應該透過 contentDescription 屬性來描述它的用途,這樣螢幕閱讀器等無障礙工具才能正確朗讀介面內容。反過來說,如果某個元素純粹是裝飾性質、不承載資訊也不觸發操作,就不需要加上描述,此時可以直接用 tools:ignore="ContentDescription" 把警告壓掉。另外要注意,輸入框(如 EditText)不要同時設定 hint 和 contentDescription,因為 hint 永遠不會顯示,只設 hint 就好。

解法:為缺少文字的元素補上 android:contentDescription 屬性,說明這個控制項的作用即可。

二、可用複合 Drawable 取代的標籤結構

報錯訊息:This tag and its children can be replaced by one and a compound drawable

當 TextView 旁邊緊挨著一個 ImageView 時,其實可以合併成一個帶有 compound drawable 的 TextView。

修改前:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="My Compound Button">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/my_drawable" />
    </TextView>
</LinearLayout>

修改後:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:drawableRight="@drawable/my_drawable"
    android:padding="5dp"
    android:text="My Compound Button" />

三、硬編碼字串

報錯訊息:Hardcoded string "計算器", should use @string resource

解法:把 XML 佈局中直接寫死的字串抽出來,統一放進 strings.xml 資源檔,再於佈局中透過 @string 的方式引用。這樣做不僅消除警告,也方便日後做多語系與翻譯維護。

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