Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: dynamically change ActionBar icon?

Tags:

I would like to dynamically change the "home" icon in the ActionBar. This is easily done in v14 with ActionBar.setIcon(...), but I can't find anyway to accomplish this in previous versions.

like image 796
ab11 Avatar asked Feb 01 '12 03:02

ab11


2 Answers

If your actionbar works like Sherlock and is based on menu items, this is my solution:

@Override public boolean onPrepareOptionsMenu(Menu menu) {     MenuItem switchButton = menu.findItem(R.id.SwitchSearchOption);          if(searchScriptDisplayed){         switchButton.setIcon(R.drawable.menu_precedent);     }else{         switchButton.setIcon(R.drawable.icon_search);     }     return super.onPrepareOptionsMenu(menu);  } 
like image 60
pommedeterresautee Avatar answered Oct 07 '22 15:10

pommedeterresautee


If you are using the ActionbarCompat code provided by google, you can access the home icon via the ActionBarHelperBase.java class for API v4 onwards.

    //code snippet from ActionBarHelperBase.java     ...     private void setupActionBar() {     final ViewGroup actionBarCompat = getActionBarCompat();     if (actionBarCompat == null) {         return;     }      LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams(             0, ViewGroup.LayoutParams.MATCH_PARENT);     springLayoutParams.weight = 1;      // Add Home button     SimpleMenu tempMenu = new SimpleMenu(mActivity);     SimpleMenuItem homeItem = new SimpleMenuItem(tempMenu,             android.R.id.home, 0, mActivity.getString(R.string.app_name));     homeItem.setIcon(R.drawable.ic_home_ftn);     addActionItemCompatFromMenuItem(homeItem);      // Add title text     TextView titleText = new TextView(mActivity, null,             R.attr.actionbarCompatTitleStyle);     titleText.setLayoutParams(springLayoutParams);     titleText.setText(mActivity.getTitle());     actionBarCompat.addView(titleText); } ... 

You should be able to modify the code to the home button accessible to the activities that extend ActionBarActivity and change it that way.

Honeycomb seems a little harder and it doesn't seem to give such easy access. At a guess, its id should also be android.R.id.home so you may be able to pull that from the view in ActionBarHelperHoneycomb.java

like image 32
Ben Neill Avatar answered Oct 07 '22 16:10

Ben Neill