Search code examples
androidandroid-glideuimenuitem

Load a remote image in a MenuItem using Glide


Usually if I want to load an image with Glide I would write the following:

Glide.with(context)
     .load(theURLOftheImage)
     .error(R.drawable.ic_error_image)
     .into(theImageView);

but what if I need to load the image of that URL into a MenuItem that has to be changed in real time?

The following is not possible because the method into does not accept the parameter:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem settingsItem = menu.findItem(R.id.actionbar_menu_profile_actions);
    if (changeImage) {
        Glide.with(this).load(theURLOftheImage).error(R.drawable.ic_error_image).into(settingsItem);
    }
    return super.onPrepareOptionsMenu(menu);
}

Solution

  • Using the approach suggested in the responses for this question worked

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem settingsItem = menu.findItem(R.id.actionbar_menu_profile_actions);
        if (changeImage) {
             Glide.with(this).asBitmap().load(theURLOfTheImage).into(new SimpleTarget<Bitmap>(100,100) {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                    settingsItem.setIcon(new BitmapDrawable(getResources(), resource));
                }
            });
        }
        return super.onPrepareOptionsMenu(menu);
    }