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

Unable to set LinearLayout BackgroundResource from URL using 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在评论中提到的那样,毕加索对目标对象的引用很弱,因此很可能会被垃圾回收。

因此,按照Jake Wharton's comment中的一个问题,我认为这可能是一个不错的选择:
  CustomLayout mCustomLayout = (CustomLayout)findViewById(R.id.custom_layout)
  Picasso.with(this).load("http://imageUrl").into(mCustomLayout);

CustomLayout.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
    }
}

10-07 19:40
查看更多