Search code examples
androidandroid-actionbarandroid-progressbarandroid-menuandroid-actionbar-compat

Show progressbar on MenuItem, even if it is on split action bar mode


I'm checking how to change the icon of a menu item to a progress bar loading animation. I tried with

<item android:id="@+id/action_favorite"
    android:icon="@drawable/ic_action_heart"
    clasificados:showAsAction="always|collapseActionView"
    clasificados:actionViewClass="android.widget.ProgressBar"/>

I'm using the split action bar mode. And when I click it, the icon dissapear and a progress bar shows it on the top bar.

What I need to change?


Solution

  • You'll need to add and remove the action view dynamically. Here's a quick example

    <item
        android:id="@+id/action_favorite"
        android:icon="@drawable/ic_action_heart"
        android:showAsAction="always" />
    

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_favorite:
                item.setActionView(new ProgressBar(this));
                item.getActionView().postDelayed(new Runnable() {
    
                    @Override
                    public void run() {
                        item.setActionView(null);
                    }
                }, 1000);
                return true;
            default:
                return false;
        }
    }
    

    About the speed of the gif, it's just the bitrate I recorded at. Example gif