使用AsyncTask加载图像

时间:2013-08-01 06:41:07

标签: java android image listview android-asynctask

我想打开我的照片,设置为代表地址(http)的字符串。创建SimpleAdapter及其传递字符串。

final ArrayList<HashMap<String,String>> CategoryList = UpdateMenuFromServer.getCategories();
final ListView ListCatalog = (ListView)findViewById(R.id.listView);
SimpleAdapter CatAdapter =new SimpleAdapter(this, CategoryList, R.layout.category_,
                    new String[] {"Name", "Image"},
                    new int[] {R.id.ProducerText, R.id.ProducerImage});

            ListCatalog.setAdapter(CatAdapter);

R.id.ProducerImage已被视为Class CustomImageView

public class CustomImageView extends ImageView{

    private static Context context;



    public CustomImageView(Context context) {
        super(context);
        this.context = context;
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }
    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
    }

    public void setImageURI (Uri uri1){
        try {
            URL url = new URL(uri1.toString());

            LoadImage load = new LoadImage(url);
            load.execute();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

        private URL Url;
        public LoadImage(URL url){
            Url = url;
        }
        @Override
        protected Drawable doInBackground(Void... voids) {
            Drawable ShowImage = null;
            try {
                ShowImage = Drawable.createFromStream(Url.openStream(), null);
            } catch (IOException e) {
                //e.printStackTrace();
            }

            return ShowImage;
        }

        protected void onPostExecute(Drawable ShowImage) {
            if(ShowImage!=null)
                setImageDrawable(ShowImage.getCurrent());
        }
    }
}

ListView在加载第一个元素时看到它改变了所有图片,然后才加载其他元素。我的问题是如何避免它并加载ListView来打开我已加载的图片。

0 个答案:

没有答案