我可以将 Picasso 的图片加载到操作栏吗?

Can I load a picture with Picasso to the action bar?

我一直在广泛使用 Picasso 通过 Internet 将图像检索到我的应用程序。现在,我 运行 遇到了需要将小图像检索到操作栏的情况(例如标题文本旁边的徽标)。

毕加索可以这样做吗?如果是这样,我该怎么做?

您可以像加载任何其他 Picasso 图像一样加载图片,但一个额外的步骤是添加自定义操作栏。类似于:

    final View actionBarLayout = getLayoutInflater().inflate(R.layout.custom_action_bar, null);

    actionBar = getSupportActionBar();
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setCustomView(actionBarLayout);

然后

 myIcon = (ImageView) actionBarLayout.findViewById(R.id.myIcon);
 Picasso.with(this).load("http://myimage.png").into(myIcon);

我找到了一个使用 Picasso Target class 并且不需要自定义操作栏的解决方案。

final ActionBar ab = getSupportActionBar();
Picasso.with(this)
       .load(imageURL)
       .into(new Target()
       {
           @Override
           public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
           {
               Drawable d = new BitmapDrawable(getResources(), bitmap);
               ab.setIcon(d);
               ab.setDisplayShowHomeEnabled(true);
               ab.setDisplayHomeAsUpEnabled(true);
           }

           @Override
           public void onBitmapFailed(Drawable errorDrawable)
           {
           }

           @Override
           public void onPrepareLoad(Drawable placeHolderDrawable)
           {
           }
       });