【问题标题】:How to add progress bar icon in action bar?如何在操作栏中添加进度条图标?
【发布时间】:2014-06-21 09:26:37
【问题描述】:

如何将进度条图标附加到显示某些 Internet 数据加载过程的操作栏? 例如:

加载数据时的图标

【问题讨论】:

标签: android


【解决方案1】:

首先,您必须创建一个自定义菜单以在您的活动中使用。 其次,您必须在“onCreate”中请求进度条功能。

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
   // rest of your code
   [....]
}//end of onCreate

然后是你的 my_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

   <item
    android:id="@+id/action_refresh"
    android:icon="@ drawable/ic_menu_refresh "
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="Refresh"
    android:visible="true"/>
</menu>

回到你的活动,你必须给这个菜单充气:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
    case R.id.action_refresh:
    // refresh icon clicked

    //show the indeterminate progress bar
    setSupportProgressBarIndeterminateVisibility(true);
    // Rest of your code to do re refresh here
    [...]
    default:
        return super.onOptionsItemSelected(item);
    }
}

PS:以上所有代码都在使用 ActionBar Compat 库。

编辑:

好的,要隐藏操作栏图标,请执行以下操作: - 在你的函数之外创建一个菜单项:

MenuItem refreshIcon;

编辑您的 onCreateOptionsMenu:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    //Initializing menu item
    refreshIcon = menu.findItem(R.id.action_refresh);
    return super.onCreateOptionsMenu(menu);
}

然后当你按下按钮改变可见性:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
    case R.id.action_refresh:
    // refresh icon clicked

    //show the indeterminate progress bar
    setSupportProgressBarIndeterminateVisibility(true);
    //hiding action icon
    refreshIcon.setVisible(false);
    // Rest of your code to do re refresh here
    [...]
    default:
        return super.onOptionsItemSelected(item);
    }
}

最后,当您的数据完成更新后,将可见性设置为“true”并隐藏进度条:

[...] //progress inside your AsyncTask or wherever you have your update
//show Refresh Icon again
refreshIcon.setVisible(true);
//hide the indeterminate progress bar
setSupportProgressBarIndeterminateVisibility(true);

【讨论】:

  • 我如何使用 setSupportProgressBarIndeterminateVisibility(true);在片段中?
  • 我找到了解决方案,但是这个进度条不会替换我的菜单图标并且永远不会停止
  • 为了访问片段内的支持栏,只需添加:getActivity.setSupport...