Android--由文件名获取文件Id的两种方法


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

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

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

这里有两种实现

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

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

二:通过反射机制:

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

  1. package com.shao.acts;  
  2.   
  3. import java.lang.reflect.Field;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7.   
  8. public class GetResIdActivity extends Activity {  
  9.     /** Called when the activity is first created. */  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.           
  15.         //方式一:   
  16.         int resId1 = getResources().getIdentifier("bluetooth""drawable""com.shao.acts");  
  17.         if(R.drawable.bluetooth==resId1){  
  18.         System.out.println("TRUE");  
  19.         }  
  20.         //方式二:   
  21.         int resId2 = getResources().getIdentifier("com.shao.acts:drawable/bluetooth"nullnull);  
  22.         if(R.drawable.bluetooth==resId2){  
  23.            System.out.println("TRUE");  
  24.         }  
  25.         //方式三:   
  26.         int resId3  = getImage("bluetooth");  
  27.         if(R.drawable.bluetooth==resId3){  
  28.             System.out.println("TRUE");  
  29.          }  
  30.     }  
  31.     public static int getImage(String pic) {  
  32.           if(pic==null||pic.trim().equals("")){  
  33.            return R.drawable.icon;  
  34.           }  
  35.           Class draw = R.drawable.class;  
  36.           try {  
  37.            Field field = draw.getDeclaredField(pic);  
  38.            return field.getInt(pic);  
  39.           } catch (SecurityException e) {  
  40.            return R.drawable.icon;  
  41.           } catch (NoSuchFieldException e) {  
  42.            return R.drawable.icon;  
  43.           } catch (IllegalArgumentException e) {  
  44.            return R.drawable.icon;  
  45.           } catch (IllegalAccessException e) {  
  46.            return R.drawable.icon;  
  47.           }  
  48.          }  
  49. }  

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

相关内容