2013-04-20 53 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