我正在尝试将图片从网站加载到图库中。图像无法加载到图库中。第一个(主)图像确实加载。
public class viewimages extends Activity {
private Gallery gallery;
private ImageView imgView;
private Integer[] Imgid = {
R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewimages);
try {
URL url = new URL("http://www.mysite.com/images/1000298/pics/1.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageBitmap(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
imgView.setImageResource(Imgid[position]);
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return Imgid.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
List<String> imageNames = new ArrayList<String>();
imageNames.add("1.jpg");
imageNames.add("2.jpg");
//etc. until you've added all images
for (int i = 0; i < imageNames.size(); i++){
URL url;
try {
url = new URL("http://www.mysite.com/images/1000298/pics/" + imageNames.get(i));
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
imgView.setImageBitmap(bmp);
imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return imgView;
}
}
}
问题似乎出现在AddImgAdp类的getView()中。我不确定这是否是尝试从网站加载图像的正确位置?
答案 0 :(得分:1)
您需要先加载所有图像。基本上你正在做的是当适配器加载时,你然后循环,尝试加载所有图像。创建一个下载图像的异步任务(我建议只将它们加载到另一个arraylist中,直到你对缓存这样的事情更加熟悉)。然后,在设置适配器时,抓住位置以使用您要查找的图像。 例如,
"imgView.setImageBitmap(imageArray.get(position))";
答案 1 :(得分:1)
今天已经存在很多android图片加载库,试着用它们来简化开发。例如https://github.com/gobozov/Android-Universal-Image-Loader