Android getIdentifier

2018-09-10  本文已影响7人  yunhen

在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);
上一篇 下一篇

猜你喜欢

热点阅读