android id数组中,android - Can I give an ID to an item in String-array? - Stack Overflow

本文探讨了如何通过将可翻译的数组条目映射到代码中的ID来避免在处理字符串数组时可能出现的ID与值的顺序错误。建议使用资源字符串为每个数组项创建ID,如@string/text_1, @string/text_2等,并在代码中将这些资源作为键ID存入哈希映射表。当需要获取特定字符串的ID时,可以通过映射表检索。这种方法确保了在使用如Spinner等组件时,能正确获取选中项的ID。
摘要由CSDN通过智能技术生成

If it is not needed to translate IDs you could map the translatable array entries to IDs in code. Advantage of that would be that you can avoid accidential order mismatches between IDs and values. For that use string resources for every array entry:

@string/text_1

@string/test_2

...

My first entry

My second entry

...

In code retrieve the string resources and put them as key + ID into a hash map:

val myArrayIdMap: HashMap = java.util.HashMap()

myArrayIdMap[getString(R.string.text_1)] = "id-1"

myArrayIdMap[getString(R.string.text_2)] = "id-2"

...

To get the ID of a specific string use the map, for example if the string array is used in a spinner, the select listener could retrieve the ID:

...

override fun onItemSelected(parent: AdapterView?, view: View?, position: Int, id: Long) {

val selectedEntry: String = parent?.getItemAtPosition(position).toString()

val id: String = myArrayIdMap.get(selectedEntry)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值