Android将图像从web加载到viewpager中

时间:2015-12-31 13:14:28

标签: android image asynchronous android-viewpager

我正在从drawable加载图片,但现在无效,我想从网上加载图片,但我被困了。我真的在寻找解决方案,但我不能成功。 有我的自定义适配器类:

int[] imageId = {R.drawable.first, R.drawable.second, R.drawable.third, R.drawable.fourth, R.drawable.fifth};

        public Object instantiateItem(ViewGroup container, int position) {
        global_position=position;

        LayoutInflater inflater = ((Activity)context).getLayoutInflater();

        View viewItem = inflater.inflate(R.layout.image_item, container, false);
        imageView = (ImageView) viewItem.findViewById(R.id.imageView);
        imageView.setImageResource(imageId[position]);
        ((ViewPager)container).addView(viewItem);
        return viewItem;
    }

如何转向它可以从网上下载图像并加载视图寻呼机。

1 个答案:

答案 0 :(得分:1)

您可以使用AsyncTask执行该作业,而不会导致应用崩溃。

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView myImage //your image url;

    public DownloadImageTask(ImageView myImage) {
        this.myImage = myImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon;
    }

    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }
}

要使用此类,只需将其与其他类一样实现。

new DownloadImageTask((ImageView) findViewById(R.id.your_image_viewer))
            .execute(imageURL);