gpt4 book ai didi

android - 使用 Picasso 将背景图片添加到 Android ListView

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:05:39 24 4
gpt4 key购买 nike

我需要向 ListView 添加背景图像。通常我会调用 listview.setBackground(myImage)。但是图像来自服务器,所以我需要使用 Picasso 将图像加载到我的 ListView 的背景中。我该怎么做?

最佳答案

选项一

定义com.squareup.picasso.Target的匿名子类

Picasso.with(yourContext)
.load(yourImageUri)
.into(new Target() {
@Override
@TargetApi(16)
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
yourListView.setBackgroundDrawable(new BitmapDrawable(bitmap));
} else {
yourListView.setBackground(new BitmapDrawable(getResources(), bitmap));
}
}

@Override
public void onBitmapFailed(Drawable errorDrawable) {
// use error drawable if desired
}

@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
// use placeholder drawable if desired
}
});

选项二

子类 ListView 并实现 com.squareup.picasso.Target

public class PicassoListView extends ListView implements Target {

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

public PicassoListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
@TargetApi(16)
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
setBackgroundDrawable(new BitmapDrawable(bitmap));
} else {
setBackground(new BitmapDrawable(getResources(), bitmap));
}
}

@Override
public void onBitmapFailed(Drawable errorDrawable) {
// use error drawable if desired
}

@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
// use placeholder drawable if desired
}

}

这让你可以这样做:

Picasso.with(yourContext)
.load(yourImageUri)
.into(yourListView);

关于android - 使用 Picasso 将背景图片添加到 Android ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26207716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com