【UI篇8】Android资源获取

461 阅读1分钟

1 获取当前APK资源

1.1 数组资源

//获取资源Id
var arr = context.resources.obtainTypedArray(R.array.resIds)
val drawableIds = IntArray(arr.length())
for (i in 0 unitl arr.length()) {
    drawableIds[i] = arr.getResourceId(i, 0)
}
arr.recycle()

1.2 通过Id获取本地资源

//获取字符串
val names = resources.getStringArray(R.array.resIds)

//获取Drawable
val drawable = AppCompatResources.getDrawable(context, resId)

1.3 获取本地图片Uri

return Uri.parse("res://" + context.packageName + "/" + drawableResId)

2 跨进程资源获取

2.1 获取其他APK的res资源

  1. 通过context.createPackageContext创建包名对应的Context
  2. 取到packageContext后通过packageContext.resources获取resources
  3. 通过resources .getIdentifier获取资源Id

具体实现

//获取包名context
val remoteContext = context.createPackageContext(pkgName, 
    Context.CONTEXT_INCLUDE_CODE or Context.CONTEXT_IGNORE_SECURITY)
if (remoteContext != null) {
    val resources = remoteContext.resources
    //更新Config
    val configuration = resources.configuration
    val displayMetrics = resources.displayMetrics
    displayMetrics.widthPixels = getRealScreenWidth()
    displayMetrics.heightPixels = getRealScreenHeight()
    displayMetrics.noncompatWidthPixels = displayMetrics.widthPixels
    displayMetrics.noncompatHeightPixels = displayMetrics.heightPixels
    resources.updateConfiguration(configuration, displayMetrics, null)

    //获取包中资源Id
    if (resources != null) {
        val resId = resources.getIdentifier("ic_welcome_home", "drawable", 
            "com.xingin.xhs")
    }
}

2.2 获取frameworks/base/core/res资源

  1. 通过context获取资源Id,获取时传入参数"bool"、"android",表示获取的框架资源
  2. 通过context.getResources().getBoolean(id)获取对应的值
final String KEY = "config_is_export";
int id = context.getResources().getIdentifier(KEY, "bool", "android");
if (id > 0) {
    isExport = context.getResources().getBoolean(id);
}