Change android icons with progress bar state to get different functions.

Himanshu Choudhary
2 min readJun 21, 2018

If you want to have more than one function of a button on the toolbar then this can be done with help of changing an image on the button. With each image, there will be a particular function which will be executed.

To change the image on the button, we will use a progress bar. You can use some other thing as per your use.

In this example, we will change the icon on the of the button as it is done in the web browser.

Step 1:

First, we will import 2 icons in the android studio drawable folder and name them as “stop” and “refresh”.

Then, define a menu in main activity as private Menu menu;

In onCreatemenuOptions, define the above menu as:

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.browser_menu, menu);
this.menu = menu;
return super.onCreateOptionsMenu(menu);
}

Step 2:

In onCreate function define this:

mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView webView, int progress) {
mProgressBar.setProgress(progress);
if (progress < 100 && mProgressBar.getVisibility() == mProgressBar.GONE) {
mProgressBar.setVisibility(mProgressBar.VISIBLE);
menu.getItem(0).setIcon(R.drawable.stop);
} else if (progress == 100) {
mProgressBar.setVisibility(mProgressBar.GONE);
menu.getItem(0).setIcon(R.drawable.refresh);
}
}
});

Step 3:

Define the different function which you need to be defined in onOptionsItemSelected as:

switch (item.getItemId()) {
case R.id.toolbar_button:
if(item.getIcon().getConstantState().equals(getResources().getDrawable(R.drawable.stop).getConstantState())){
mWebView.stopLoading();
}else if (item.getIcon().getConstantState().equals(getResources().getDrawable(R.drawable.refresh).getConstantState())){
mWebView.reload();
}else if (item.getIcon().getConstantState().equals(getResources().getDrawable(R.drawable.default_icon).getConstantState())){
thirdFunction();
}
break;
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response