转自:http://blog.csdn.net/shaojie519/article/details/6746716


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

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

一:通过android已有的方法getIdentifier (String name, String defType, String defPackage)方法。

该方法调用方式有两种:

a.int resId1 = getResources().getIdentifier("bluetooth", "drawable", "com.shao.acts");

b.int resId2 = getResources().getIdentifier("com.shao.acts:drawable/bluetooth", null, null);


二:通过反射机制:

假定 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");//包名可以通过方法activity.getPackageName()获得        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;      }     }}


更多相关文章

  1. Android(安卓)Framework AIDL的使用
  2. Android新线程中更新主线程UI中的View方法汇总
  3. Android(安卓)进程间通信 实例分析
  4. Android(安卓)ContentProvider和Uri详解
  5. Android(安卓)更新UI的两种方法——handler和runOnUiThread()
  6. Android消息处理机制
  7. Android(安卓)EditText 禁止软键盘弹出
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. android 下动态获取控件的id
  2. android 監聽系統屬性變化的方法
  3. Android LCD
  4. Android:调用系统分享功能
  5. zz Android HTML5 video play
  6. android notification 的例子
  7. NDK调试
  8. android 获得当前活动的Acticity
  9. Android打造带删除的EditText并且实现输
  10. Android基于名称、修改时间、大小实现文