android--由文件名获取文件Id的两种方法
2011-09-04 10:34
597 查看
在android中,我们经常使用资源文件的id来代替这个资源,如 R.drawable.*** ,
那怎样通过文件名得到这个资源的Id的,这里介绍两种方法:
一:通过 getIdentifier (String name, String defType, String defPackage)方法。
这里有两种实现
1.name 用package:type/entry,那么后面两个参数可以为null.
2.name只写文件名,后面两参数分别为文件类型和包路径。
二:通过反射机制:
给个demo: drawable文件夹中有一bluetooth.png图片。
输出都为true.不信可以试试,O(∩_∩)O~
那怎样通过文件名得到这个资源的Id的,这里介绍两种方法:
一:通过 getIdentifier (String name, String defType, String defPackage)方法。
这里有两种实现
1.name 用package:type/entry,那么后面两个参数可以为null.
2.name只写文件名,后面两参数分别为文件类型和包路径。
二:通过反射机制:
给个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中由文件名获取文件Id的两种方法
- Android中由文件名获取文件Id的两种方法
- android--由文件名获取文件Id的两种方法
- Android根据资源文件名获取它的资源ID 的两种方式
- android应用 获取本地指定类型文件 的两种最优方法
- Android根据图片文件名获取它的资源ID 的两种方式
- android获取文件getMimeType的两种方法
- Android 用 res 中文件名获取资源 id 的方法
- Android根据图片文件名获取它的资源ID 的两种方式
- Android根据图片文件名获取它的资源ID 的两种方式
- android应用 获取本地指定类型文件 的两种最优方法
- android获取文件getMimeType的两种方法
- android应用 获取本地指定类型文件 的两种最优方法
- android应用 获取本地指定类型文件 的两种最优方法
- android获取图片尺寸的两种方法以及bitmap的缩放
- Android开发:获取屏幕宽和高的两种方法(px、dip、分辨率之间的关系及px与dip互相转化)
- Android工程内嵌资源文件的两种方法
- Android使用getIdentifier()获取资源Id的方法
- Android获取手机输入法ID的方法