[Android] styles.xmlで指定しているattr先のidentifierIdを知りたい!

drawableのidentifierの値と、attrで指定した同じdrawableのidentifierを取りたかったんだけど、attrのidentifierとdrawableのidentifierは別物だったので、どうにかして、attrで指定しているdrawableのidentifierをとりたい!!ってことで調べたのでそのメモ。
答えは下記にあった。
cf: Access resource defined in theme and attrs.xml android
例えば以下の感じで指定しているstyles.xmlがあったとする。
1 2 3 4 |
<style name="OfficialAppTheme" parent="AppTheme"> <item name="hoge">@drawable/official_hoge</item> </style> <attr name="hoge" format="reference" /> |
こんなかんじでdrawableのidentifierはとれます
1 |
val identifier = context.resources.getIdentifier("official_hoge", "drawable", context.packageName) |
上記と同じidentifierをattrからとるには、下記のようにひっぱてくる模様。
1 2 3 4 |
val styleIdentifier = context.resources.getIdentifier("OfficialAppTheme", "style", context.packageName) val attrIdentifier = context.resources.getIdentifier("hoge", "attr", context.packageName) val styleAttributes = context.theme.obtainStyledAttributes(styleIdentifier, intArrayOf(attrIdentifier)) val hogeIdentifier = styleAttributes.getResourceId(0, 0) |
ちょっと遠回りですがこんなかんじでとれますた。