Android 资源名获取R文件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;
        }
    }

Android 资源名获取R文件id_第1张图片
Android 资源名获取R文件id_第2张图片

Parameters

name The name of the desired resource.
defType Optional default resource type to find, if “type/” is not included in the name. Can be null to require an explicit type.
defPackage Optional 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.)

你可能感兴趣的:(Android)