基于 URL 更新 ImageView

Updating ImageView based on URL

我花了很多时间浏览关于这个主题的多个不同线程,但我还没有找到适合我的代码的答案(Android SDK 23,2016 年)。许多答案已被弃用,而其他答案则完全无法正常工作,我想知道我是否可以就此得到可靠的答案:

我想在我的 Serebii 程序中包含一个 Pokemon 精灵(静态图像)。 nums 是一个变量,指示口袋妖怪的 dex 编号(我保证这个功能正常)。这段代码在主 UI 线程中 运行,我知道这是不受欢迎的,但现在我正在尝试加载图像,然后降低应用程序的流畅度。 我本身并不真的需要位图,但我需要我的 ImageView 来更新和显示 URL 提供的图像。我该怎么做?

URL url = null;
try {
     url = new URL("http://www.serebii.net/xy/pokemon/" + nums + ".png");
} catch (MalformedURLException e) {
  e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
mImageView.setImageBitmap(bmp);

您可以尝试将 Picasso 用作:

Picasso.with(context)
          .load(url)
          .into(imageview);

或者使用 Universal Image loader 作为:

 ImageLoader imageLoader = new  ImageLoader(context);
 imageLoader.displayImage(imageUri, imageView);

只需使用 Picasso 库,它将完成所有图像加载。您只需要正确提供图片的url即可。

String url = "http://www.serebii.net/xy/pokemon/" + nums + ".png";

Picasso.with(yourContext)
    .load(url)
    .into(mImageView);

为此使用 Piassco 库..Library link

用于在 ImageView

上设置 Bitmap
Picasso.with(getContext()).load("your url").into(new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            //do what ever you want with your bitmap 
          imgView.setImageBitmap(loadedImage);///imgView is use to set the image in it
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    });

还有Picasso的另一种方法:-

Picasso.with(this)
        .load("your_image_url")
        .placeholder(R.drawable.no_image)
        .error(android.R.drawable.stat_notify_error)
        .networkPolicy(NetworkPolicy.OFFLINE)//user this for offline support
        .into(YOUR_IMAEGVIEW);

您也可以使用 Universal Image Loader..这是 link Universal image loader

ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
            imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
              DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.YOUR_DRAWABLE)
                    .showImageForEmptyUri(R.drawable.YOUR_DRAWABLE)
                    .showImageOnFail(R.drawable.YOUR_DRAWABLE)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .considerExifParams(true)
                    .build();

imageLoader.displayImage("your_image_url", YOUR_IMAGEVIEW, null);

您可以使用 Picasso 库加载图像。
a) 将 Gradle 添加到您的项目中。

compile 'com.squareup.picasso:picasso:2.5.2'

b) 用法

Picasso.with(context).load("http://www.serebii.net/xy/pokemon/" + nums + ".png").into(imageView);

还有其他的库,你可以像这样使用 Fresco by Facebook, Universal Image loader