Android 资源名获取R文件id

本文介绍了一种在Android开发中通过资源名称获取对应资源ID的方法,即使用`getResources().getIdentifier()`函数。该方法允许开发者通过指定资源的名字、类型及包名来获取资源ID,适用于图片、字符串和颜色等不同类型的资源。

也就是通过res文件夹下的资源名称获取R文件里面生成的id, 这个id用起来和在代码中使用R.XXX.XXX一样.

获取方法为:

    getResources().getIdentifier(String name, String defType, String defPackage)

上图上代码

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_setImage:
                int imageId = getResources().getIdentifier("image", "drawable", getPackageName());
                mImage.setImageResource(imageId);
                break;
            case R.id.btn_setText:
                int textId = getResources().getIdentifier("text", "string", getPackageName());
                mBtnSetText.setText(textId);
                break;
            case R.id.btn_setColor:
                int colorId = getResources().getIdentifier("colorPrimary", "color", getPackageName());
                mBtnSetColor.setTextColor(getResources().getColor(colorId));
                break;
            default:
                break;
        }
    }

这里写图片描述
这里写图片描述

Parameters

nameThe name of the desired resource.
defTypeOptional default resource type to find, if “type/” is not included in the name. Can be null to require an explicit type.
defPackageOptional default package to find, if “package:” is not included in the name. Can be null to require an explicit package.

Returns

int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值