2012年3月12日 星期一

String to Drawable


String 轉 drawable:

e.g. 1


private void displayImage() {

String uri = "drawable/imagefile01"; 
 // int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(uri, null, getPackageName()); 
ImageView imageView = (ImageView) findViewById(R.id.myImageView); 
Drawable image = getResources().getDrawable(imageResource); imageView.setImageDrawable(image);
 }

***********************************************

e.g.2 應用在 database + ListAdapter
假設圖檔放在 res/drawable/ 下,其檔名則是以字串方式存在 database 裡。可以下列方式將之顯現出來:



Cursor c = getData();
c.moveToFirst();

String [] imgStrings = new String [c.getCount()]; //將存放從db來的圖檔名
int [] imgResources = new int [c.getCount()];//準備將字串轉成整數格式 
Object [] imgObj = new Object [c.getCount()];//準備接收成 Drawable 的物件

for (int i = 0; i < str1.length; i++){
  imgStrings [i] = c.getString(0);//圖形檔名後接有 .png
 //將存在db的圖檔字串檔名轉成drawable
 String uri = "drawable/" + str2[i].substring(0, str2[i].length()-4).toString(); 
 // 刪掉後頭的 .png (四個位元)
 imgResources[i] = getResources().getIdentifier(uri, null, getPackageName());
 imgObj [i] = getResources().getDrawable(imgResources[i]);
c.moveToNext();
}
c.close(); 
/CustomAdapter. 將得到的drawable 物件陣列,傳入自己設定的adapter 
ArrayAdapter<String> adapter = new CustomAdapter(this, imgObj); 
setListAdapter(adapter);


&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


CustomAdapter.java 自己設定的 Adapter:

public class CustomAdapter extends ArrayAdapter<String>{

 private LayoutInflater inflater;
 private final Context context;

private final Object [] img; //來接收傳進來的drawable 物件陣列

public EventAdapter(Context context, Object [] imgObj) { //Constructor
 super(context, R.layout.eventlayout, event);
 this.context = context; 
 this.img = imgObj;
}
@Override

public View getView(int position, View convertView, ViewGroup parent) {

   ViewHolder holder = new ViewHolder(); 
   inflater = LayoutInflater.from(context); 
   View rowview = inflater.inflate(R.layout.eventlayout, parent, false);
   holder.imageview = (ImageView)rowview.findViewById(R.id.ImageView01); 
   Object drawable = img[position]; //將Object 型態轉為 Drawable
   holder.imageview.setImageDrawable((Drawable) drawable);
   return rowview;
   } 

    static class ViewHolder
    ImageView imageview;
    }

}

沒有留言:

張貼留言