android - 如何使用 Picasso 加载布局背景

标签 android android-layout picasso

谁能给我指出一个示例,说明如何使用 Picasso 以编程方式更改 XML 布局的背景?我发现的所有示例都能够使用 Picasso 更新 ImageView - 但不能更新布局背景。

Unable to set LinearLayout BackgroundResource from URL using Picasso

最佳答案

你可以使用 picasso 的目标:

         Picasso.with(this).load("http://imageUrl").into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
               mYourLayout.setBackground(new BitmapDrawable(bitmap));
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        });

更新

正如@BladeCoder 在评论中提到的,Picasso 持有对 Target 对象的弱引用,因此它很可能被垃圾收集。

所以,关注 Jake Wharton's comment关于其中一个问题,我认为这可能是一个很好的方法:

  CustomLayout mCustomLayout = (CustomLayout)findViewById(R.id.custom_layout)
  Picasso.with(this).load("http://imageUrl").into(mCustomLayout);

自定义布局.java:

public class CustomLayout extends LinearLayout implements Target {

    public CustomLayout(Context context) {
        super(context);
    }

    public CustomLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        setBackground(new BitmapDrawable(getResources(), bitmap));
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {
        //Set your error drawable
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        //Set your placeholder
    }
}

关于android - 如何使用 Picasso 加载布局背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31464867/

相关文章:

Android WebView 有时不会在初始页面加载时发送请求 header

iphone - 是否有同时适用于 iphone 和 android 应用程序的图表库?

android - 如何从重定向到 https 的 http URL 下载图像?

android - 如何在可折叠工具栏中使用viewpager?

android - 如何让水平 Linear Layout Child 包裹其内容?

android - 从 Picasso 获取重定向 URL

android - picasso - 如何加载矢量绘图?

android - 如何在 Android 中向 WebServer 发送数据?

java - 每当我向远程数据库添加内容时如何通知应用程序用户?

android - android中不同布局与不同值文件的优势