Replacing an ActionBar menu item icon with an indeterminate ProgressBar

≯℡__Kan透↙ 提交于 2019-11-30 06:28:58

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.

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.

aga

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

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.

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

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