我有gridview,必须将图像下载到gridview。当我打开应用程序时,我看不到任何图像,但我认为我的代码在某种程度上是正确的。怎么解决? 我在我的适配器中使用此代码:
// 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
//float wd = 250 / Resources.getSystem().getDisplayMetrics().density;
//float hg = 300 / Resources.getSystem().getDisplayMetrics().density;
int pxwd = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 90, Resources.getSystem().getDisplayMetrics());
int pxhg = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 120, Resources.getSystem().getDisplayMetrics());
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(pxwd, pxhg));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(LoadImageFromURL(GridViewConfig.getImage_list().get(position)));
return imageView;
}
// references to our images
private Drawable LoadImageFromURL(String url)
{
try {
InputStream is = (InputStream) new URL(url).getContent();
return Drawable.createFromStream(is, "src");
} catch (Exception e) {
return null;
}
}
这里是网址列表:
public class GridViewConfig {
public static ArrayList<String> image_listGrid = new ArrayList<String>();
public static ArrayList<String> getImage_list() {
return image_listGrid;
}
public static void setImage_list(ArrayList<String> image_list) {
GridViewConfig.image_listGrid = image_list;
}
public static void addImageUrls(){
image_listGrid.add("someimage.jpg");
}
但问题是我的GridView上没有显示图像。
答案 0 :(得分:0)
在getView(...)
中,您应该使用TypedValue.COMPLEX_UNIT_DIP
替换TypedValue.COMPLEX_UNIT_SP
:
int pxwd = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 90, Resources.getSystem().getDisplayMetrics());
int pxhg = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, Resources.getSystem().getDisplayMetrics());
希望这有帮助!