Load a remote image in a MenuItem using Glide

白昼怎懂夜的黑 提交于 2019-12-10 21:33:53

问题


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);
}

回答1:


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).load(theURLOfTheImage).asBitmap().into(new SimpleTarget<Bitmap>(100,100) {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                settingsItem.setIcon(new BitmapDrawable(getResources(), resource));
            }
        });
    }
    return super.onPrepareOptionsMenu(menu);
}



回答2:


Another approach from one of my codings populating a BottomNavigationView:

    ...
    bottomNavigationView = findViewById(R.id.bottomNavigationView);

    if(bottomNavigationView != null) {

        bottomNavigationView.inflateMenu(R.menu.bottom_main_menu);

        Menu bottomMenu = bottomNavigationView.getMenu();

        //bottomMenu.removeItem(0);

        final MenuItem menuItem = bottomMenu.add("Test 95");

        Glide
                .with(this)
                .load("https:// <add your image resource link here>")
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        menuItem.setIcon(resource);
                    }
                });

    }
    ...

remember to add correct Glide version in app gradle, 4.7.1 should work with this one:

   implementation 'com.github.bumptech.glide:glide:4.7.1'


来源:https://stackoverflow.com/questions/37116247/load-a-remote-image-in-a-menuitem-using-glide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!