简体   繁体   中英

Replacing an ActionBar menu item icon with an indeterminate ProgressBar

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?

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.

为了简化larham1的答案 :你甚至不需要夸大新的动作视图本身,因为MenuItem有接受动作布局id 的方法 ,所以你可以简单地写:

item.setActionView(R.layout.progress_bar);

很难准确地说出电子邮件应用程序是如何做到的,但您可能希望保持简单,只需使用StateDrawable XML文件的id调用setIcon ,然后使用Timer更改状态。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM