如何在代码中使用picasso设置背景图像

Toy*_*oye 25 java android android-scrollview picasso android-relativelayout

我知道毕加索将图像加载到imageview等,但如何使用毕加索设置我的布局背景图像?

我的代码:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativelayout);
        relativeLayout.setBackgroundResource(R.drawable.table_background);
        Picasso.with(MainActivity.this)
                .load(R.drawable.table_background)
                .resize(200, 200)
                .into(relativeLayout);
        return relativeLayout;
    }
Run Code Online (Sandbox Code Playgroud)

我在这里给出了任何错误,说它无法解决.我有一个ScrollView和相对布局.

Soh*_*ham 59

使用毕加索的回调

    Picasso.with(getActivity()).load(R.drawable.table_background).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)

更新:

请检查一下.正如@OlivierH在评论中提到的那样.

  • 小心:正如[本回答](http://stackoverflow.com/a/31464960/2806497)中所提到的,"毕加索对Target对象有一个弱引用,因此很可能是垃圾收集. (2认同)