Android Toggle Button in ActionBar

Is there a way to put a ToggleButton in an ActionBar and make it keep the state it is in, so when you reopen the same activity, it is in the same state as you left it?

Optional: If possible, Android 2.3.3 - 2.3.7 backward compatible

+4
source share
2 answers

First, define the layout containing 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 continue:

Using the layoput action:

 <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> 

Software upgrade: In Activity or Snippet :

 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); 
+1
source

You can use ActionBar.setCustomView() and pass it to Switch or ToggleButton , although I don't know if this will work along with other ActionBar navigation modes. As for storing this value, just save it in SharedPreferences and set it again when the action is created.

Regarding backward compatibility, you have two options: the ActionBarSherlock library or the new Google v7 support .

0
source

Source: https://habr.com/ru/post/1495829/


All Articles