Android, getting resource ID from string?

后端 未结 14 1637
忘掉有多难
忘掉有多难 2020-11-21 23:56

I need to pass a resource ID to a method in one of my classes. It needs to use both the id that the reference points to and also it needs the string. How should I best achie

14条回答
  •  眼角桃花
    2020-11-22 00:20

    The Kotlin approach

    inline fun > T.getId(resourceName: String): Int {
                return try {
                    val idField = getDeclaredField (resourceName)
                    idField.getInt(idField)
                } catch (e:Exception) {
                    e.printStackTrace()
                    -1
                }
            }
    

    Usage:

    val resId = R.drawable::class.java.getId("icon")
    

提交回复
热议问题