2011-04-27 105 views
1

我想用圖標動態地填充gridview。我遵循gridview hello教程。然而,圖像陣列並不總是完全一樣的。根據之前的動作,給出由圖標名稱構成的不同的image array(從肥皂響應中提取),例如, agenda => agenda.png。我想通過在數組中循環並將其與R.drawable + icon_name相加來創建該數組。但是R.drawable無法解析到所請求的Integer數組。解析錯誤 - Android java

public class ImageAdapter extends BaseAdapter 
{ 
    private Context mContext; 
    final ArrayList<String> image = getIntent().getStringArrayListExtra("image"); 

    public ImageAdapter(Context c) { 
     mContext = c; 
    } 

    public int getCount() { 
     return icoontjes.size(); 
    } 

    public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

    public ArrayList<Integer> icoontjes; 
    { 
     for (int i=0; i<image.size(); i++){ 
      Integer icon= Integer.valueOf("R.drawable."+image.get(i)); 
      icoontjes.add(icon); 
     } 
    } 

    // create a new ImageView for each item referenced by the Adapter 
    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView imageView; 
     if (convertView == null) { // if it's not recycled, initialize some attributes 
      imageView = new ImageView(mContext); 
      imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); 
      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
      imageView.setPadding(8, 8, 8, 8); 
     } else { 
      imageView = (ImageView) convertView; 
     } 

     imageView.setImageResource(icoontjes.get(position)); 
     return imageView; 
    } 
} 

回答

3

您可以使用

for (int i=0; i < image.size(); i++) { 
    Integer icon = getResources().getIdentifier(image.get(i), "drawable", "your.package"); 
    icoontjes.add(icon); 
} 

其中your.package是您的Android應用程序的基本包(您已定義您的static final R class的包。

這種方式的icon變量會根據您的image.get(i)保存您的drawable的id。

+0

這種方法看起來更好 – Selvin 2011-04-27 13:39:40

+0

thx爲我工作! – Swellwave 2011-05-03 11:20:02

1

我可以給ü一個答案,但你不應該(實在不應該)做...

,而不是

Integer icon= Integer.valueOf("R.drawable."+image.get(i)); 

嘗試

R.class.getField("R.drawable."+image.get(i)).getInt(null)