Reputation: 674
How I can attach icon of progress bar to action bar that display loading process of some Internet data? For example:
And icon while load data
Upvotes: 1
Views: 2148
Reputation: 433
First of all you have to create a custom menu to use inside your activity. Secondly, you have to request the feature of progress bar inside your "onCreate".
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
// rest of your code
[....]
}//end of onCreate
Then your 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>
Back to your activity, you have to inflate this 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: All the above code is working using the ActionBar Compat Library.
EDIT:
Ok, to hide the action bar icon do this: -Create a menuitem outside your functions:
MenuItem refreshIcon;
Edit your 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);
}
Then when you press the button change the visibility:
@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);
}
}
Finally, when your data is finished updating set the visibility to "true" and hide progressbar:
[...] //progress inside your AsyncTask or wherever you have your update
//show Refresh Icon again
refreshIcon.setVisible(true);
//hide the indeterminate progress bar
setSupportProgressBarIndeterminateVisibility(true);
Upvotes: 3