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

Android setTag 方法 key 問題的解決辦法

編輯:關於 Android 程式設計

Android 在設計 View 類時,為了能儲存一些輔助資訊,特別提供了 setTag/getTag 方法。這讓我聯想到 Winform 設計中,每個 Control 同樣存在一個 Tag。

今天要說的是我最近學習 Android 時遇到的 setTag 的坑。一般情況下我們只需使用單參數的 setTag 方法;但有時需要儲存多個數據,這時就得使用帶 key 的重載版本。

官方文檔的描述是:「 The specified key should be an id declared in the resources of the application to ensure it is unique. Keys identified as belonging to the Android framework or not associated with any package will cause an IllegalArgumentException to be thrown.」

這裡說明必須保證 key 的唯一性。但如果我們用 java 常量定義 key(如 private static final int TAG_ID = 1;),你依然會遇到如下錯誤:

java.lang.IllegalArgumentException: The key must be an application-specific resource id

正確的解決方案是:在 res/values/strings.xml 中定義這個 key 常量,如下:

 <resources> <item type="id" name="tag_first"></item> <item type="id" name="tag_second"></item> </resources> 

使用方式如下:

 imageView.setTag(R.id.tag_first, "Hello"); imageView.setTag(R.id.tag_second, "Success"); 

以上就是對 Android setTag 方法 key 問題的解決辦法,謝謝大家對本站的支持!

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