如何在操作栏中添加进度条图标?

时间:2014-06-21 09:26:37

标签: android

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

enter image description here

加载数据时的图标

enter image description here

1 个答案:

答案 0 :(得分:2)

首先,您必须创建一个自定义菜单才能在您的活动中使用。 其次,您必须在" 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 Library。

编辑:

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

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

最后,当您的数据完成更新时,将可见性设置为&#34; true&#34;并隐藏进度条:

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