概述

tools 這個命名空間通常是在 xml 檔案的一開始定義的,例如在 AndroidManifest.xml 中:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    ...

tools 的主要用途是給 Lint 這個程式碼規範檢核工具用的,Lint 會檢查我們的程式,看看是否有不符合規範的地方,然後給出提示。tools:ignore 可以讓 Lint 怱略這些不合規範的地方。

tools:ignore 的使用範例

ScopedStorage

在 Android 10 (API Level 29)之後,WRITE_EXTERNAL_STORAGE 並沒有實質的作用,所以 Lint 會給出提示訊息,如果不想看到這訊息,可以加上 tools:ignore="ScopedStorage"

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    tools:ignore="ScopedStorage" />

我們也可以明確的指定這個值只適用到 API Level 28,這樣 Lint 也不會有提示訊息。(建議使用此方法)

<uses-permission 
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="28"/>

HardCodedText

如果我們在字串中直接輸入資料,而非使用 string 資源,就會有提示訊息,如果不想看到提示訊息出現,可以使用 tools:ignore="HardCodedText

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello world" />

上述的程式碼在 Android Studio 會提示你要將字串萃取成 字串資源。

但是當我們加入 tools:ignore="HardCodedText 到 TextView 或其上層元素中,這個提示訊息就不會出現。

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="HardCodedText"
        android:text="Hello world" />

參考資料

Android Studio User Guide: Tools attributes reference

Android Studio User Guide: Improve your code with lint checks

Android:Tools命名空间原来是有大用处的

Last modified: 2023 年 3 月 25 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.