Search code examples
androidandroid-actionbarmenuitem

Setting MenuItem icon from URL - Android


I want to set a MenuItem in my ActionBar which leads to the user profile page in my app. I would like the icon for that to be his profile picture for which I have the URL and can create a BitMap out of.

The image isn't stored in my project folder or anywhere locally so I can't pick it up from R.drawable.

Can somebody help me with setting a bitmap created with the URL as the MenuItem icon? Thanks for the help!


Solution

  • You could do something like this to set the icon from a bitmap:

    myMenuItem.setIcon(new BitmapDrawable(getResources(), myBitmap));
    

    In your code this would looks a bit like this:

    public boolean onCreateOptionsMenu( Menu menu ) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate( R.menu.actionbar, menu );
        userItem = menu.findItem(R.id.userItem);
    
        Bitmap myBitmap = //get your bitmap
        userItem.setIcon(new BitmapDrawable(getResources(), myBitmap));
    
        return menu;
    }
    

    You'll need to get the file from the URL and turn it into a Bitmap first. Note that this will be slow, since if you are doing this when your app is started, the user will have to wait until the file is downloaded before the app will be shown. If your icon changes infrequently, I'd recommend caching it on the device and reusing the locally stored copy.

    Also check the "Changing the menus at runtime" section here.