我正在尝试在 ImageSwitcher 中显示来自 URL 的图像。我试过:
myImageSwitcher.setImageURI(Uri.parse("http://miurl.com/images/foto01.jpg "));
但它告诉我这个“错误”:
I/System.out:resolveUri 在错误的位图 uri 上失败:http://miurl.com/images/foto01.jpg
谢谢
最佳答案
我知道已经晚了,但因为我找到了更好的解决方案,很乐意与所有人分享 :)
我必须查看默认 ImageSwitcher
的源代码并了解它是如何工作的。每当我们使用 ImageSwitcher
时,我们都会为它设置一个 ViewFactory
。此 ViewFactory
创建 View
,然后在 ImageSwitcher
中使用。通常我们在ViewFactory
中创建一个ImageView
。然后在 ImageSwitcher
类中使用此 ImageView
来绘制具有指定图像源的 View 。下面是 ImageSwitcher
类的 setImageResource()
方法。
public void setImageResource(@DrawableRes int resid){
ImageView image = (ImageView)this.getNextView();
image.setImageResource(resid);
showNext();
}
让我们关注方法的第一行和第二行。
ImageView image = (ImageView)this.getNextView();
image.setImageResource(resid);
this.getNextView()
从 ViewFactory
获取 View 并将 View 转换为 ImageView
。然后,为它设置 Drawable 资源。
解决方案
现在,有了这些信息,我们就可以找到解决方案了!我使用的是 Volley 的 NetworkImageView
,但您也可以使用 Picasso 或 Glide!您只需稍微更改一下代码即可。
我们需要创建一个自定义 ImageSwitcher。这是我的代码
MyImageSwitcher.java
public class MyImageSwitcher extends ImageSwitcher {
public MyImageSwitcher(Context context) {
super(context);
}
public MyImageSwitcher(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setImageUrl(String url) {
NetworkImageView image = (NetworkImageView) this.getNextView();
image.setImageUrl(url, AppController.getInstance().getImageLoader());
showNext();
}
}
注意 setImageUrl()
方法。我们将从 getNextView()
获得的 View 转换为 NetworkImageView
并为其设置 Url。如果您想使用 Picasso,只需将其转换为 ImageView
,然后在需要使用时使用 Picasso。
Activity
MyImageSwitcher imageSwitcher = (MyImageSwitcher) findViewById(R.id.imageSwitcher);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
NetworkImageView myView = new NetworkImageView(getApplicationContext());
myView.setScaleType(ImageView.ScaleType.CENTER_CROP);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(imageSwitcher.getLayoutParams()));
return myView;
}
});
如果您想使用 Picasso,只需使用 ImageView
。
布局
<xyz.farhanfarooqui.loadingimages.MyImageSwitcher
android:id="@+id/imageSwitcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
AndroidManifest.xml
不要忘记将 android.permission.INTERNET
包含到您的 AndroidManifest.xml
完成!
每当你想改变图像时,就这样做,
imageSwitcher.setImageUrl("http://miurl.com/images/foto01.jpg");
关于android - ImageSwitcher 从 url 加载图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27296414/