Replacing an ActionBar menu item icon with an inde

2019-02-04 13:48发布

问题:

I would like to add an indeterminate progress bar to the Honeycomb ActionBar, so that any time the user presses "Refresh", the refresh icon temporarily turns into an indeterminate progress bar, until the task completes. The Email app does this already, but I can't figure out how.

Any advice?

回答1:

Hard to tell exactly how the Email app does it, but you may want to stay simple and just call setIcon with the id of a StateDrawable XML file, and then just change the state using a Timer.



回答2:

To clarify Jon O's answer, the key is to set and unset an action view on the refresh action. This works in both ActionBarSherlock and native 4.x action bar. The following snippet will put the progress indeterminate view on top of the refresh icon, assuming the refresh menu item has ID 'refresh_option' and the replacement layout (which has a ProgressBar) is in layout 'progress_wheel':

 MenuItem item = abmenu.findItem(R.id.refresh_option);
 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View abprogress = inflater.inflate(R.layout.progress_wheel, null);
 item.setActionView(abprogress);

Unset the progress view, and the refresh icon will return to visibility:

 item.setActionView(null);

See a more detailed example on github.



回答3:

It turns out that Google has posted an example of doing exactly this as a part of their broader ActionBarCompat compatibility project. Have a look.



回答4:

To simplify larham1's answer: you don't even need to inflate new action view itself because MenuItem has the method which accepts id of action layout, so you can simply write:

item.setActionView(R.layout.progress_bar);


回答5:

I'm using the code provided at the original issue here: https://github.com/JakeWharton/ActionBarSherlock/issues/425

Except for android:layout_width and android:layout_height (in the actionbar_indeterminate_progress.xml) I use 32dp; as this was the way it was done in ActionBarCompat: http://developer.android.com/resources/samples/ActionBarCompat/res/layout-v11/actionbar_indeterminate_progress.html



回答6:

You can easily do it by:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_refresh: 
                item.setActionView(new ProgressBar(this));
                break;
        }
        return super.onOptionsItemSelected(item);