Jak*_*est 1 android android-fragments picasso
我正在尝试使用Picasso进行更简单的图像内存管理.我刚刚尝试在我的片段中实现它,但我似乎无法让它工作.
mainLayout.setBackground(new BitmapDrawable(getResources(), Picasso.with(mainLayout.getContext()).load(R.drawable.background2).get()));
Run Code Online (Sandbox Code Playgroud)
其中mainLayout是LinearLayout.我也试过这个:
Picasso.with(getActivity().getApplicationContext()).load(R.drawable.background2).into(imageView1);
Run Code Online (Sandbox Code Playgroud)
我试过Picasso.with(这个)......但这根本不起作用.
我一直得到一个例外:
java.lang.IllegalStateException: Method call should not happen from the main thread.
at com.squareup.picasso.Utils.checkNotMain(Utils.java:71)
at com.squareup.picasso.RequestCreator.get(RequestCreator.java:206)
at ...
Run Code Online (Sandbox Code Playgroud)
在哪里我打电话给它.
有人经历过这个或知道如何正确使用碎片?
小智 9
异常消息表明它非常清楚..get()消息不是异步的,因此将在主线程上完成工作(网络,读取文件......等),尽可能避免.
但是,将图像设置为imageView的代码对我来说似乎是正确的.
我认为也可以对mainLayout做同样的事情(Picasso会自动将drawable/Bitmap设置为背景).如果我在这里错了,请看看Picasso附带的Target.class.您可以将图像加载到目标中,该目标必须为成功和错误提供处理程序.在成功处理程序中,您将在加载后获取位图并将其设置为您的bakground.
有一些解决方案可能适用于您的情况.
[编辑]
当使用Picasso提供的get()方法时,加载将在您当前使用的线程中进行,这在源代码中有明确说明:https: //github.com/square/picasso/blob/master/picasso/的src/main/JAVA/COM/squareup /毕加索/ RequestCreator.java
/**同步满足此请求.不得从主线程调用.*/
public Bitmap get()抛出IOException {[...]}
在你的情况下,我会使用Target接口,它在加载图像时提供回调.
Picasso.with(getActivity()).load(R.drawable.background2).into(new Target(){
@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
mainLayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
@Override
public void onBitmapFailed(final Drawable errorDrawable) {
Log.d("TAG", "FAILED");
}
@Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
Log.d("TAG", "Prepare Load");
}
});
Run Code Online (Sandbox Code Playgroud)
在这里使用内部资源时,为什么不执行以下操作?
mainLayout.setBackgroundResource(R.drawable.background2);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
问候
归档时间: |
|
查看次数: |
9013 次 |
最近记录: |