2013-04-20 46 views
0

我所有的圖像都存儲在可繪製的文件夾中。我希望看到一些圖像的圖庫視圖。用字符串數組設置圖庫[圖像名稱]

我想要的圖像的名稱是在一個字符串數組中。

我可以通過圖庫視圖來顯示這些圖像嗎?

我發現代碼在下面,這裏的圖像是一個整數。

我可以使用字符串數組嗎?

public class ImageAdapter extends BaseAdapter { 

    private Context context; 

    public ImageAdapter(Context context){ 
     this.context = context; 
    } 

    public int getCount() { 
     return pics.length; 
    } 

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

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

    public View getView(int arg0, View arg1, ViewGroup arg2) { 
     ImageView iv = new ImageView(context); 
     iv.setImageResource(pics); 
     iv.setScaleType(ImageView.ScaleType.FIT_XY); 
     iv.setLayoutParams(new Gallery.LayoutParams(150,120)); 
     iv.setBackgroundResource(imageBackground); 
     return iv; 
    } 
} 
+0

我在代碼中看不到任何字符串數組。無論如何,你應該添加一個構造函數,它接收一個字符串數組,然後使用[this link](http://stackoverflow.com/a/3044081/896038) – 2013-04-20 15:45:39

回答

0

如果您的圖片在您的資源中,這很容易。

public class ImageAdapter extends BaseAdapter { 

    private Context context; 
    private Resources resources; 

    private String[] imageNames; 

    public ImageAdapter(Context context, String[] imageNames){ 
     this.context = context; 
     this.resources = context.getResources(); 
     this.imageNames = imageNames; 
    } 

    public int getCount(){ 
     return imageNames.length; 
    } 

    public String getItem(int position){ 
     return imageNames[position]; 
    } 

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

    public View getView(ViewGroup parent, View convertView, int position){ 
     if(convertView == null){ 
      convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageview, parent, false); 
     } 
     int imageId = resources.getIdentifier(getItem(position), "drawable", context.getPackageName()); 
     ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview); 
     imageView.setImageResource(imageId); 
     return convertView; 
    } 
} 
+0

thks作爲響應!我再次遇到問題!我不能說明到底發生了什麼......我寫了,但我有問題在getView函數..在int imageId = resources.getIdentifier(getItem(position),「drawable」,context.getPackage()) ;和imageView.setDrawable(imageId);對於第一個沒有擴展getPackage,只有getPackageManager但我不能使用,因爲indetifiner(字符串,字符串,字符串)。對於第二行,沒有例外setDrawable。 – george 2013-04-22 13:58:41

+0

哎呀,看看編輯。 – alex 2013-04-22 14:11:00

+0

> **謝謝!!!! ** – george 2013-04-22 15:45:07