使用 Picasso 库,我通过 url 加载位图。 这是我的代码:
MainActivity.java
public class MainActivity extends AppCompatActivity{
private String imageUrl = "https://images.unsplash.com/photo-1532793647389-1d8cf566cae6?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=e2bd210796f1313a943261973b470ae8&auto=format&fit=crop&w=700&q=80";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Picasso.get()
.load(imageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.d("MyLog", "BitmapLoaded");
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
但这段代码不适用于我的真实设计。 “onBitmapLoaded”没有被调用。
但是当我在我的模拟器上运行这个应用程序时,它在第二次尝试时运行。
我不明白为什么会这样?
最佳答案
我认为这是因为; Picasso
将 Target
作为弱引用
。您能否尝试将您的 Target
定义为类中的全局变量并重新加载图像?
private final Target myTarget = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.d("MyLog", "BitmapLoaded");
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
然后加载如下:
Picasso.get()
.load(imageUrl)
.into(myTarget);
这样你的 Target
对象就有了强引用并且不会被 GC
立即收集。
关于java - 毕加索。第二次尝试时加载的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583899/