Android根据图片文件名获取它的资源ID 的两种方式


http://topmanopensource.iteye.com/blog/1600321


     假如在drawable目录下放一个图片文件,由于一些原因,我们在程序中仅仅知道它的文件名,而不知道它的资源ID,当我们需要这个资源ID的时候,可以使用下面的一行代码获取到:

方法一:

Java代码   收藏代码
  1.   /** 
  2.    * 获取图片名称获取图片的资源id的方法 
  3.    * @param imageName 
  4.    * @return 
  5.    */  
  6.  public int  getResource(String imageName){  
  7. Context ctx=getBaseContext();  
  8. int resId = getResources().getIdentifier(imageName, "drawable" , ctx.getPackageName());  
  9. return resId;  

 方法二:

Java代码   收藏代码
  1. /** 
  2.  * 获取图片名称获取图片的资源id的方法 
  3.  * @param imageName 
  4.  * @return 
  5.  */  
  6. public int getResourceByReflect(String imageName){  
  7.     Class drawable  =  R.drawable.class;  
  8.        Field field = null;  
  9.        int r_id ;  
  10.        try {  
  11.            field = drawable.getField(imageName);  
  12.            r_id = field.getInt(field.getName());  
  13.        } catch (Exception e) {  
  14.         r_id=R.drawable.b_nothing;  
  15.            Log.e("ERROR""PICTURE NOT FOUND!");  
  16.        }  
  17.        return r_id;  
  18. }  

 

 

知道资源ID,获取资源的文件名

  1. getResources().getResourceName(resid)  

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用以下方法来根据文件名获取文件路径: 1. 遍历设备上的文件系统,搜索匹配的文件名。 ```java public String getFilePathByFileName(String fileName) { File rootDir = Environment.getExternalStorageDirectory(); // 获取外部存储根目录 String filePath = searchFile(rootDir, fileName); return filePath; } private String searchFile(File file, String fileName) { if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (File child : files) { String filePath = searchFile(child, fileName); if (filePath != null) { return filePath; } } } } else { if (file.getName().equals(fileName)) { return file.getAbsolutePath(); } } return null; } ``` 2. 使用 ContentResolver 查询匹配的文件。 ```java public String getFilePathByFileName(String fileName, Context context) { Uri uri = MediaStore.Files.getContentUri("external"); String[] projection = {MediaStore.Files.FileColumns.DATA}; String selection = MediaStore.Files.FileColumns.DISPLAY_NAME + "=?"; String[] selectionArgs = {fileName}; Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA); String filePath = cursor.getString(columnIndex); cursor.close(); return filePath; } return null; } ``` 这两种方法分别通过遍历文件系统和查询 ContentResolver 来获取文件路径。注意,在使用这些方法之前,确保你已经获取了相应的权限,例如读取外部存储的权限。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值