如何通过编程获取属性ID?及从attr变量提取属性引用名?
Great questions! Let's break this down step by step for Android development:
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.
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

