Android中動態(tài)設(shè)置資源id,通過反射以字符串"R.layout.xxx"設(shè)置資源

一些不常見的場景,獲取到的資源是服務(wù)端下發(fā)字符串 "R.layout.sleep_activity","R.anim.fly_up"形式。
或者寫Demo的時(shí)候,一個(gè)Activity對應(yīng)多個(gè)布局,希望以外部傳入字符串形式設(shè)置 setContentView(layout)。比如以下:

無標(biāo)題.png

傳遞給目標(biāo)Activity一個(gè)字符串“R.layout.xxx”,而本地對應(yīng)的布局xxx有多個(gè),需要加載到同一個(gè)目標(biāo)Activity
方法之一是通過反射,從R資源類獲取想要的“R.layout.xxx” 的int值,再setContentView(it)

/**
     *  應(yīng)用:
     *  val layoutIdInt = Util.getIdByName(context, "layout", "R.layout.sleep_activity")
     * */
fun getIdByName(context: Context, typeName: String, name: String): Int {
        val packageName = context.packageName
        var id = 0
        try {
            val r = Class.forName("$packageName.R")
            val resTypes = r.classes
            var dstClass: Class<*>? = null

            // Search if has type we need?
            for (i in resTypes.indices) {

                // resTypes[i] is the type of resource, eg. "com.jesen.cod.layoutadvanced.R$anim"
                // end is typeName, eg. "anim"
                val end = resTypes[i].name.split("\\$").toTypedArray()[1]
                if (end == typeName) {
                    dstClass = resTypes[i]
                    break
                }
            }

            // Yes, find the type
            if (dstClass != null) {
                val simpleName = name.split("\\.").toTypedArray()[2]
                val f = dstClass.getField(simpleName)

                //f.setAccessible(true);
                Log.d("XXX", "getIdByName, f : $f")
                id = f.getInt(dstClass)
            }
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } catch (e: SecurityException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        }
        return id
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容