从Custom Spinner上的URL显示图像

时间:2014-01-26 05:31:49

标签: android asynchronous imageview spinner

我已经构建了一个自定义微调器,每行包含一个ImageView。当我直接从本地存储的现有drawable加载图像时,这一切都很完美。但我的目标是从URL中获取这些图像,理想情况下是懒惰,因为图像可能对任何行都是唯一的。这就是我现在所拥有的:

 public View getCustomView(int position, View convertView, ViewGroup parent) {

     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     View row = inflater.inflate(R.layout.row, parent, false);

     ImageView this_picture = (ImageView)row.findViewById(R.id.image);
     Drawable d = LoadImageFromWebOperations("fake_person");

     if (d == null) {
         System.err.println("no image");
     } else{
         this_picture.setImageDrawable(d);
     }

     TextView label = (TextView) row.findViewById(R.id.name);
     label.setText(my_list.get(position));

     return row;
 }

 public static Drawable LoadImageFromWebOperations(String this_name) {

     try {
         InputStream is = (InputStream) new URL("https://www.mobilenicity.com/silhouette_male.png").getContent();
         Drawable d = Drawable.createFromStream(is, "src name"); 
         return d;
     } catch (Exception e) {
         return null;
     }
}

这将始终返回图像的空值(日志输出no image)。我很确定这是因为url调用没有及时返回,但我不知道如何解决这个问题。任何建议表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

你应该使用AsyncTask,如下所示:

public class LoadImage extends AsyncTask <Void , Void , Drawable > {

private String imageUrl ; 
private ImageView imageView ; 

public LoadImage(String url , ImageView imageView ){
this.imageUrl = url ;
this.imageView = imageView ;
}

 protected Drawable doInBackground(Void... params) {    

try {
         InputStream is = (InputStream) new URL(this.imageUrl).getContent();
         Drawable d = Drawable.createFromStream(is, "src name"); 
         return d;
     } catch (Exception e) {
         return null;
     }

}  



       protected void onPostExecute(Drawable result) {      
    imageView.setImageDrawable(result); 
    } 

}

并从适配器中的getView方法中调用它,如下所示:

new LoadImage(url , imageView).execute();

希望有所帮助。