Android 资源名获取资源ID的两种实现方式-附带例子说明

获取资源文件,res目录下的资源时,id报空指针!!!如何解决?

之前一直纠结的问题,如何获取资源的id??


在android中,我们经常使用资源文件的id来代替这个资源,如 R.drawable.*** ,

那怎样通过文件名得到这个资源的Id的,这里介绍两种方法:

一:通过  getIdentifier (String name, String defType, String defPackage)方法。

  这里有两种实现

1.name 用package:type/entry,那么后面两个参数可以为null.

2.name只写文件名,后面两参数分别为文件类型和包路径。


栗子来了。。。
package com.taobao.serv1;
import android.content.Context;
/**
 * Created by apple on 16/9/7.
 */
public class Utils  {

    public static int getResource(Context context, String name, String type) {
        try {
            String packageName = context.getPackageName();
            return context.getResources().getIdentifier(name, type, packageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}

使用举栗子:

Utils.getResource(context, "selectorDialog", "style") //style里的文件名称
Utils.getResource(context, "jxt_sdk_dialog_towebpage", "layout") //style里的文件名称里的文件名称
Utils.getResource(context, "jxt_sdk_dialog_towebpage_btn_ok", "id") //id里的文件名称


原来google已经提供了这个极好用的方法。。

源码:

   /**
     * Return a resource identifier for the given resource name.  A fully
     * qualified resource name is of the form "package:type/entry".  The first
     * two components (package and type) are optional if defType and
     * defPackage, respectively, are specified here.
     * 
     * 

Note: use of this function is discouraged. It is much more * efficient to retrieve resources by identifier than by name. * * @param name The name of the desired resource. * @param defType Optional default resource type to find, if "type/" is * not included in the name. Can be null to require an * explicit type. * @param defPackage Optional default package to find, if "package:" is * not included in the name. Can be null to require an * explicit package. * * @return int The associated resource identifier. Returns 0 if no such * resource was found. (0 is not a valid resource ID.) */ 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); }


二:通过反射机制: 没有验证(摘自网络)

给个demo:    drawable文件夹中有一bluetooth.png图片。

package com.shao.acts;  
  
import java.lang.reflect.Field;  
  
import android.app.Activity;  
import android.os.Bundle;  
  
public class GetResIdActivity extends Activity {  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
        //方式一:  
        int resId1 = getResources().getIdentifier("bluetooth", "drawable", "com.shao.acts");  
        if(R.drawable.bluetooth==resId1){  
        System.out.println("TRUE");  
        }  
        //方式二:  
        int resId2 = getResources().getIdentifier("com.shao.acts:drawable/bluetooth", null, null);  
        if(R.drawable.bluetooth==resId2){  
           System.out.println("TRUE");  
        }  
        //方式三:  
        int resId3  = getImage("bluetooth");  
        if(R.drawable.bluetooth==resId3){  
            System.out.println("TRUE");  
         }  
    }  
    public static int getImage(String pic) {  
          if(pic==null||pic.trim().equals("")){  
           return R.drawable.icon;  
          }  
          Class draw = R.drawable.class;  
          try {  
           Field field = draw.getDeclaredField(pic);  
           return field.getInt(pic);  
          } catch (SecurityException e) {  
           return R.drawable.icon;  
          } catch (NoSuchFieldException e) {  
           return R.drawable.icon;  
          } catch (IllegalArgumentException e) {  
           return R.drawable.icon;  
          } catch (IllegalAccessException e) {  
           return R.drawable.icon;  
          }  
         }  
} 

输出都为true.不信可以试试,O(∩_∩)O~

你可能感兴趣的:(Android积累)