美文网首页
通过name获取资源ID

通过name获取资源ID

作者: sexyhair | 来源:发表于2018-11-10 15:36 被阅读0次

APP中需求:根据用户的国家码展示用户所在国家图标,国家图片有300多张,这个就需要根根资源的name拿到对应的资源ID

Kotlin - 工具类代码

object ResourceUtil {
    val RES_STRING = "string"//表示拿的是string类型的资源ID
    val RES_DRAWABLE = "drawable"
    val RES_LAYOUT = "layout"

    fun getResId(context: Context, resType:String,imageName: String): Int {
        //如果没有则返回0
        return context.resources.getIdentifier(imageName, resType, context.packageName)
    }
}
使用:
var resId = ResourceUtil.getResId(this, ResourceUtil.RES_DRAWABLE, "icon_" + code)

Kotlin 设置国家码的方法

fun setCountryIcon(code: String, textView: TextView) {
    if (!code.isNullOrEmpty()) {
        var resId = ResourceUtil.getResId(this, ResourceUtil.RES_DRAWABLE, "icon_" + code)
        if (resId != 0) {
            var drawable = AppCompatResources.getDrawable(applicationContext, resId)
            if (drawable != null) {
                drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
                textView.compoundDrawablePadding = DimenUtils.dp2px(3f)
                textView.setCompoundDrawables(drawable, null, null, null)
            }
        }
    }
}

参考链接:https://blog.csdn.net/love667767/article/details/79426543

相关文章

网友评论

      本文标题:通过name获取资源ID

      本文链接:https://www.haomeiwen.com/subject/kjqxtqtx.html