<Android>关于获取资源文件R中的数据

通常我们都会使用context.getResources().getIdentifier(name, type,context.getPackageName())的方法去获取R.java中的数据。

type——R其中的内部类名,如"drawable","string","color","dimen","layout"等,这也是我们常用的关于界面所需要获取的数据类型。

name——R内部类中的static变量名称,如"appname"等,这些都是有用户在xml文件中定义的,包括layout,drawable文件中xml的文件名称。

最后一个参数就是apk的包名。

其实为何使用context.getResources().getIdentifier来获取资源的数值,很简单,在开发属于自己的sdk的时候,因为你的资源文件和jar包供给其他人使用,在界面方面自然都会使用此方法来获取资源对应数值。

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

/**

 * 对于context.getResources().getIdentifier无法获取的数据,或者数组

 * 资源反射值

 * @paramcontext

 * @param name

 * @param type

 * @return

 */

private static Object getResourceId(Context context,String name, String type) {

String className = context.getPackageName() +".R";

try {

Class<?> cls = Class.forName(className);

for (Class<?> childClass : cls.getClasses()) {

String simple = childClass.getSimpleName();

if (simple.equals(type)) {

for (Field field : childClass.getFields()) {

String fieldName = field.getName();

if (fieldName.equals(name)) {

System.out.println(fieldName);

return field.get(null);

}

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

 *context.getResources().getIdentifier无法获取到styleable的数据

 * @paramcontext

 * @param name

 * @return

 */

public static int getStyleable(Context context, Stringname) {

return ((Integer)getResourceId(context, name,"styleable")).intValue();

}

 

/**

 * 获取styleableID号数组

 * @paramcontext

 * @param name

 * @return

 */

public static int[] getStyleableArray(Context context,String name) {

return (int[])getResourceId(context, name,"styleable");

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值