You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程获取属性ID?及从attr变量提取属性引用名?

Great questions! Let's break this down step by step for Android development:

1. Can you programmatically get an attribute's ID?

Absolutely! You can use the Resources.getIdentifier() method to fetch the integer ID of an attribute by its name. Here's a practical Kotlin example:

val targetAttributeName = "textAppearanceHeadline1"
val attributeId = resources.getIdentifier(
    targetAttributeName,
    "attr",
    packageName
)

if (attributeId != 0) {
    // Success: attributeId now holds the integer ID for textAppearanceHeadline1
} else {
    // Oops: no attribute with that name exists in your project
}

A quick note: The method returns 0 if the attribute can't be found, so always add that check to avoid unexpected behavior.

2. How to get the attribute name "textAppearanceHeadline1" from the variable attr = R.attr.textAppearanceHeadline1?

To convert the integer attribute ID back to its human-readable name, use Resources.getResourceEntryName(). This method takes the resource ID and returns the exact entry name as a string. Here's how to use it:

val attr = R.attr.textAppearanceHeadline1
val attributeName = resources.getResourceEntryName(attr)
// attributeName will be "textAppearanceHeadline1"

Just a heads-up: If the ID doesn't map to a valid resource, this will throw a Resources.NotFoundException. For safer handling, wrap it in a try-catch block:

val attr = R.attr.textAppearanceHeadline1
val attributeName = try {
    resources.getResourceEntryName(attr)
} catch (e: Resources.NotFoundException) {
    "Invalid attribute ID provided"
}

内容的提问来源于stack exchange,提问作者user12507977

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:32:53