How to get a resource id with a known resource name?

前端 未结 10 1270
挽巷
挽巷 2020-11-21 23:31

I want to access a resource like a String or a Drawable by its name and not its int id.

Which method would I use for this?

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 00:13

    Kotlin Version via Extension Function

    To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

    ExtensionFunctions.kt

    import android.content.Context
    import android.content.res.Resources
    
    fun Context.resIdByName(resIdName: String?, resType: String): Int {
        resIdName?.let {
            return resources.getIdentifier(it, resType, packageName)
        }
        throw Resources.NotFoundException()
    }
    


    Usage

    Now all resource ids are accessible wherever you have a context reference using resIdByName method:

    val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
    val stringResId = context.resIdByName("title_home", "string")
    .
    .
    .    
    

提交回复
热议问题