背景设置的方法以及通过文件名来获取drowable文件夹中图片id的方法

例如 要设置背景的画面的xml的名称为bglist.xml,其中Layout的id为background_list_layout,

LayoutInflater mInflater = LayoutInflater.from(context);
View convertView = mInflater.inflate(R.layout.bglist, null);
LinearLayout background = convertView.findViewById(R.id.background_list_layout)

如果背景图为设置在项目中drowable文件夹下的文件的话:
background.setBackgroundResource(R.id.icon);
如果背景图片为某个路径下的图片文件的话:
String url = "/mnt/sdcard/DCIM/abcd-2.jpg"
Drawable image = Drawable.createFromPath(url);
background.setBackgroundDrawable(image);
// -------------------------------------------------------------------------------------------------------------------------
有时候我们需要通过文件名来获取在drowable文件夹下文件的相应id,作法有一下几种
参考网址:http://blog.csdn.net/shaojie519/article/details/6746716

一:通过  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;  
           }  
          }  
 }  


http://blog.csdn.net/kmyhy/article/details/6583804

posted @ 2012-05-07 13:30  日光之下无新事  阅读(438)  评论(0编辑  收藏  举报