谁能给我指出一个示例,说明如何使用 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/