Android通过反射获取资源ID

摘要:
˃<resources><declare styleable name=“TestMySelfTextView”><attrname=“myTextColor”format=“color”></attr><attrname=“myTextSize”format=”dimension“/˃<attrname=“myString”format=“string”/></resources>R文件中styleable子类中的属性字段格式:publicstaticfinalclassstyleable{publicstaticfinalint〔〕TestMySelfTextView={0x7f01000a,0x7f00100b,0x7f 01000c};publicstaticfinaintTestMySelfTextView_myTextColor=0;publicstaticfinaintTestMySelfTextView_myTextSize=1;publicstaticfinaintTestMySelfTextView_myString=2;}读取方法:遍历R类以获取可样式数组资源1下的子资源。首先找到R类下的可样式子类,2。遍历styleable类以获取字段值,并根据名称获取int数组:publicstaticint[]getStyleableIntArray{try{field[]fields=class.forName.getFields();//。和$difference,$表示R的子类{if{int[]=field.get;return;}}catch{e.printStackTrace();}return null;}使用int数组获取TypeArray:调用Context#objectStyledAttributes(),参数attrs是自定义视图的构造函数。输入参数int[]a=ResourceId。getStyleableIntArray;TypedArraytypedArray=context.getgetStyledAttributes;通过TypeArray#getString():typedArray获取配置资源。getString获取资源ID的方式与获取styleableint数组的方式不同。这里,直接返回int值:/***遍历R类以获取可样式数组资源下的子资源。1.首先找到R类下的可样式子类,2。遍历styleable类以获得字段值**@paramcontext*@paramstyleableName*@paramtyleableFieldName*@return*/publicstatisticentgetStyleableFieldId{StringclassName=context.getPackageName()+“.R”;Stringtype=“styleable”;Stringname=styleableName+“_”+styleableFieldName;try{class˂?

通过反射获取布局文件:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        int id = this.getResources().getIdentifier("layout_test", "layout", this.getPackageName());
       
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(id, null);
        
        setContentView(view);
}

使用getResources().getIdentifier(),传入三个参数:布局文件名,资源类型,包名;返回值为资源的ID。

使用:包名+“:”+“layout/layout_name”获取layout控件:

int id =getResources().getIdentifier(getPackageName()+":layout/layout_test",null,null);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(id, null);
setContentView(view);

使用ID获取控件:

int imageViewId = getResources().getIdentifier("id_layout_test_image", "id", getPackageName());
ImageView imageView = (ImageView) findViewById(imageViewId);

使用图片名获取图片:

 int drawableId = getResources().getIdentifier("bjmgf_sdk_cup", "drawable", getPackageName());
 Drawable res = getResources().getDrawable(drawableId);

或者使用URI获取图片:

String uri = "@drawable/bjmgf_sdk_cup";
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);

在开发属于自己的控件,用到了attr自定义属性,在期间发现一个问题,即styleable的数值无法使用context.getResources().getIdentifier来获取,结果永远都是0,而且styleable中还包括数组数据,所以最后还是用java的反射方法来获取

xml文件中的定义格式:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TestMySelfTextView">
        <attr name="myTextColor" format="color"></attr>
        <attr name="myTextSize" format="dimension" />
        <attr name="myString" format="string" />

    </declare-styleable>
</resources>

R文件中的styleable子类中的属性字段格式:

public static final class styleable {
 public static final int[] TestMySelfTextView= {
            0x7f01000a, 0x7f01000b,0x7f01000c
        };
 public static final int TestMySelfTextView_myTextColor = 0;
 public static final int TestMySelfTextView_myTextSize = 1;
 public static final int TestMySelfTextView_myString = 2;
}

读取方式:遍历R类得到styleable数组资源下的子资源,1.先找到R类下的styleable子类,2.遍历styleable类获得字段值

根据名字获取int数组:

public static int[] getStyleableIntArray(Context context, String name) {
        try {
            Field[] fields = Class.forName(context.getPackageName() + ".R$styleable").getFields();//.与$ difference,$表示R的子类
            for (Field field : fields) {
                if (field.getName().equals(name)) {
                    int ret[] = (int[]) field.get(null);
                    return ret;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

利用int数组,获得TypeArray:调用Context#obtainStyledAttributes(),参数attrs是自定义view的构造器传入参数

 int[] a = ResourceId.getStyleableIntArray(context, "TestMySelfTextView");
 TypedArray typedArray = context.obtainStyledAttributes(attrs, a);

 通过TypeArray#getString()获取配置资源:

typedArray.getString(ResourceId.getStyleableFieldId(context, "TestMySelfTextView", "myString"))

这里获取资源ID的方式和获取styleable int数组不同,这里直接返回int值:

/**
     * 遍历R类得到styleable数组资源下的子资源,1.先找到R类下的styleable子类,2.遍历styleable类获得字段值
     *
     * @param context
     * @param styleableName
     * @param styleableFieldName
     * @return
     */
    public static int getStyleableFieldId(Context context, String styleableName, String styleableFieldName) {
        String className = context.getPackageName() + ".R";
        String type = "styleable";
        String name = styleableName + "_" + styleableFieldName;
        try {
            Class<?> cla = Class.forName(className);
            for (Class<?> childClass : cla.getClasses()) {
                String simpleName = childClass.getSimpleName();
                if (simpleName.equals(type)) {
                    for (Field field : childClass.getFields()) {
                        String fieldName = field.getName();
                        if (fieldName.equals(name)) {
                            return (int) field.get(null);
                        }
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return 0;
    }

免责声明:文章转载自《Android通过反射获取资源ID》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇《深度剖析CPython解释器》20. Python类机制的深度解析(第四部分): 实例对象的创建、以及属性访问在.net core 的webapi项目中将对象序列化成json下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

使用C#写MVC框架(一:核心原理) HttpHandler

https://www.cnblogs.com/pandorabox/p/10477426.html 使用C#写MVC框架(一:核心原理) 目录: 一、MVC原理解析 二、HttpHandler        1.HttpHandler,IHttpHandler,MvcHandler的说明        2.IHttpHandler解析        3...

安卓架构

1、架构图直观 下面这张图展示了Android系统的主要组成部分: 图1、Android系统架构(来源于:android sdk) 可以很明显看出,Android系统架构由5部分组成,分别是:Linux Kernel、Android Runtime、Libraries、Application Framework、Applications。第二部分将详细...

老李分享:Android -自动化埋点 3

又一个问题,代码中的writeLog方法到底要记录哪些数据作为log信息呢?log信息中最重要的是能让开发者看出来哪个界面被打开或者哪个控件被点 击。对于界面,可以记录其类名;对于控件,一般没有确定的名称,那么可以记录下来这个控件在界面中的路径。比如上文中介绍Android UI布局的实例,如果要定位记录那个Button,则可以记录它所在界面的类名和But...

Android 换肤

导读:皮肤程序的AndroidManifest.xml中配置 皮肤一般含有多个文件,例如图片、配置等文件,分散的文件不利于传输和使用,最好打包。打包的格式一般选择zip格式。这里分两种情况,一种是apk,例如AdwLauncher,它的桌面皮肤格式是一个apk;另一种是自定义扩展名,例如墨迹天气皮肤扩展名是mja,搜狗输入法的皮肤扩展名是sga,它们的文...

C#开发Android应用实战 读后感

最近两年从事C#网站和项目开发比较多,JAVA项目比较少了,没有经历过手机开发项目的经验。手上也有两部Android、HTC智能手机,喜欢手机客户端上部分软件的功能,自己也想开发一个类似小说阅读器手机端的搜集IT技术文章的手机软件。特申请一本《C#开发Android应用实战》来学习和阅读。年前一月三十一号拿到此书,因为手头还有WCF等技术一直在学习和实践,...

二维码扫描开源库ZXing定制化【转】

转自:http://www.cnblogs.com/sickworm/p/4562081.html 最近在用ZXing这个开源库做二维码的扫描模块,开发过程的一些代码修改和裁剪的经验和大家分享一下。 建议: 如果需要集成到自己的app上,而不是做一个demo,不推荐用ZXing的Android外围开发模块,只用核心的core目录的代码就好了。androi...