Android getIdentifier

在Android开发的过程中我们需要动态的根据一个资源名获得到对应的资源id,我们可以使用getResources().getIdentifier()方法来获取该id, 然后通过该id进行相应的操作。

Resources resources = getResources();
        //获取布局文件的Id
        int mainLayout = resources.getIdentifier("activity_main", "layout", getPackageName());
        setContentView(mainLayout);
        //获取TextView 的id
        int txtId = resources.getIdentifier("author", "id", getPackageName());
        //获取字符串id
        int strId = resources.getIdentifier("author", "string", getPackageName());
        //获取Drawable id
        int drawableId = resources.getIdentifier("text_bg", "drawable", getPackageName());
        TextView textView = (TextView) findViewById(txtId);
        textView.setText(strId);
        textView.setBackground(ContextCompat.getDrawable(this, drawableId));

        //ImageView id
        int imgId = resources.getIdentifier("launcher_icon", "id", getPackageName());
        //mipmap id
        int mipmapId = resources.getIdentifier("ic_launcher", "mipmap", getPackageName());
        ImageView imageView = (ImageView) findViewById(imgId);
        imageView.setImageResource(mipmapId);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容