5

Android中通过反射获取资源Id

 3 years ago
source link: http://www.androidchina.net/3679.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Android中通过反射获取资源Id – Android开发中文站
你的位置:Android开发中文站 > Android开发 > 新手入门 > Android中通过反射获取资源Id

在将自己写的工具打成.jar包的时候,有时候会需要引用到res中的资源,这时候不能将资源一起打包,只能通过反射机制动态的获取资源.

特别用在自己定义一个工具将其打成.jar包时,特别注意资源的获取

1、封装成一个工具类 

package com.cp.utils;
import android.content.Context;
public class CPResourceUtil {
public static int getLayoutId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString, "layout",
paramContext.getPackageName());
}
public static int getStringId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString, "string",
paramContext.getPackageName());
}
public static int getDrawableId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"drawable", paramContext.getPackageName());
}
public static int getStyleId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"style", paramContext.getPackageName());
}
public static int getId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,"id", paramContext.getPackageName());
}
public static int getColorId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"color", paramContext.getPackageName());
}
public static int getArrayId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"array", paramContext.getPackageName());
}
}

2、资源的获取

<string name="version_update_schedule">已下载%1$s请稍等&#8230;</string>
String text=mContext.getResources().getString(CPResourceUtil.getStringId(mContext, "version_update_schedule"));

TextView.setText(String.format(text, p+”%”));

version_update_schedule 是string文件中name

转载请注明:Android开发中文站 » Android中通过反射获取资源Id


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK