您的位置:首页 > 移动开发 > Android开发

android使用获取所有应用的资源id和uri

2016-06-29 10:35 357 查看
在某些应用中,为了实现应用apk资源放入重复利用,或者使用反射得到本应用的资源,需要使用反射反射方式获得,但Resources类中也自带了这种获取方式,并且功能更加强大

你可以获取string,color,drawable,raw,xml等文件,因此也就意味着,这里可以获取的资源是res中已定义的资源,对于控件id的获取,暂时无法做到

android.content.res.Resources.class

 public int getIdentifier(String name, String defType, String defPackage) {
        if (name == null) {
            throw new NullPointerException("name is null");
        }
        try {
            return Integer.parseInt(name);
        } catch (Exception e) {
            // Ignore
        }
        return mAssets.getResourceIdentifier(name, defType, defPackage);
    }


一.获取资源的id
1.如下,我们可以获取当前应用的资源id

 int drawableId = mContext.getResources().getIdentifier("ic_launcher","drawable", mContext.getPackageName());
 mImageView.setImageResource(drawableId);

2.我们也可以获取其他应用的资源id

Resources resources = context.getResources();
int indentify= getResources().getIdentifier("icon", "drawable", "org.anddev.android.testproject");

int resId = getResources().getIdentifier("background", "color", getPackageName());
startBtn.setTextColor(getResources().getColor(resId));

对于这种方式,我们也可以这么做

int indentify = getResources().getIdentifier(org.loveandroid.androidtest:drawable/icon",null,null);


3.进行封装一下

public static int getResourceId(Context context,String name,String type,String packageName){
        Resources themeResources=null;
        PackageManager pm=context.getPackageManager();
        try {
            themeResources=pm.getResourcesForApplication(packageName);
            return themeResources.getIdentifier(name, type, packageName);
        } catch (NameNotFoundException e) {

            e.printStackTrace();
        }
        return 0;
 }


二.获取资源的uri
android系统中,应用的资源存储时也通常会被存入 数据库,也可以被共享,因此来说资源会获得应用的uri

Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.xinyueshenhua);
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.drawable.ic_launcher);

我们也可以进一步封装

public static  Uri getResourceUri(int resId,String packageName)
{
    return Uri.parse("android.resource://"+packageName+"/"+resId);
}


三.获取系统资源

int indentify = getResources().getIdentifier("actionbar_bg", "drawable","android");  //注意,最后一个参数必须是“android”


© 著作权归作者所有
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: