Android setTag方法的key問題解決辦法
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 (see the ID resource type). Keys identified as belonging to the Android framework or not associated with any package will cause an IllegalArgumentExceptionto 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問題的解決辦法,謝謝大家對本站的支持!
- Android開發(fā) -- setTag的妙用和The key must be an application-specific resource id 異常
- Android實現上拉加載更多ListView(PulmListView)
- Android onNewIntent()觸發(fā)機制及注意事項
- Android Intent 用法全面總結及實例代碼
- 三行Android代碼實現白天夜間模式流暢切換
- Android通過JNI實現守護進程
- Android仿淘寶商品拖動查看詳情及標題欄漸變功能
- Android自定義ActionProvider ToolBar實現Menu小紅點
- Android 安全加密:對稱加密詳解
相關文章
Android scrollToTop實現點擊回到頂部(兼容PullTorefreshScrollview)
當頁面滑動到底部,出現回到頂部的按鈕相信對大家來說并不陌生,下面這篇文章主要介紹了關于Android scrollToTop實現點擊回到頂部,并兼容PullTorefreshScrollview的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒。2017-03-03Android使用CrashHandler來獲取應用的crash信息的方法
本篇文章主要介紹了Android使用CrashHandler來獲取應用的crash信息的方法,具有一定的參考價值,有興趣的可以了解一下2017-09-09