Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Toggle Button in ActionBar

Is there a way to put a ToggleButton in the ActionBar and get it to save what state it is in, so when you open the same activity again it is in the same state as you left it?

Extra: If possible have android 2.3.3 - 2.3.7 backward compatibility

like image 393
richie_south Avatar asked Nov 03 '22 17:11

richie_south


1 Answers

First define a layout that contains your Toggle:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
  <ToggleButton
    android:id="@+id/actionbar_service_toggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="Logging On"
    android:textOff="Logging Off" />
</RelativeLayout>

Then you have two alternatives to proceed:

Using an action layoput:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/myswitch"
        android:title=""
        android:showAsAction="always"
        android:actionLayout="@layout/actionbar_service_toggle" />   
</menu>

Inflating programmatically: In your Activity or Fragment you do:

ActionBar actionBar = getSupportActionBar();
actionBar.setCustomView(R.layout.actionbar_top);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM);
...
ToggleButton button = (ToggleButton) findViewById(R.id.actionbar_service_toggle);
like image 138
Rudolf Real Avatar answered Nov 11 '22 12:11

Rudolf Real