Replacing an ActionBar menu item icon with an indeterminate ProgressBar

后端 未结 6 967
小蘑菇
小蘑菇 2020-12-30 02:29

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 indet

相关标签:
6条回答
  • 2020-12-30 03:05

    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.

    0 讨论(0)
  • 2020-12-30 03:06

    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.

    0 讨论(0)
  • 2020-12-30 03:07

    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.

    0 讨论(0)
  • 2020-12-30 03:08

    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);
    
    0 讨论(0)
  • 2020-12-30 03:09

    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);
    
    0 讨论(0)
  • 2020-12-30 03:16

    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

    0 讨论(0)
提交回复
热议问题