Is it possible to Implement Toggle Button in Action Menu Item using Actionbar sherlock in android

RajeshVijayakumar picture RajeshVijayakumar · Feb 19, 2013 · Viewed 22.3k times · Source

I have an app, which have toggle button in action menu item, though i'm using Actionbar Sherlock, I don't know, how to place the toggle button in the action menu item. I don't want to place as a custom layout in action bar, but i want to place it as a Menu item. If anyone find solution, Please help me out.

Purpose, If I change the state of toggle button, it will sort the person based on ALphabets and again in Date of Birth.

Thanks in Advance!

Answer

Yalla T. picture Yalla T. · Feb 19, 2013

Just add it like a normal Menu Button, check its state with a boolean variable, and you can change the icon and title when changing the sortmode

boolean birthSort=false;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_toggle:

        if(birthSort){
            //change your view and sort it by Alphabet
            item.setIcon(icon1)
            item.setTitle(title1)
            birthSort=false;
        }else{
            //change your view and sort it by Date of Birth
            item.setIcon(icon2)
            item.setTitle(title2)
            birthSort=true;
        }
        return true;



    }
    return super.onOptionsItemSelected(item);


}

Don't forget to add it in xml like any other menu button and configure android:showAsAction if you want to show it in overflow or outside of it.

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

<item android:id="@+id/menu_toogle"
    android:showAsAction="ifRoom"
    android:title="Share"
     />
</menu>