Android使用getIdentifier()方法根据资源名来获取资源id

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

使用方法如下:

1、工程目录如下:

2、MainActivity代码如下:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        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);
    }
}
3、布局文件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:id="@+id/author"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:padding="5dp" />

    <ImageView
        android:id="@+id/launcher_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_below="@id/author" />

</RelativeLayout>
4、strings.xml字符串资源代码如下:
<resources>
    <string name="app_name">ResouceId</string>
    <string name="author">Owen Chan Blog</string>
</resources>
5、真机上运行结果

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值