有没有办法将ToggleButton放在ActionBar中,并让它保存其状态,这样当您再次打开相同的活动时,它的状态与您离开时相同?
附加: 如果可能的话,请向后兼容Android 2.3.3-2.3.7。
有没有办法将ToggleButton放在ActionBar中,并让它保存其状态,这样当您再次打开相同的活动时,它的状态与您离开时相同?
附加: 如果可能的话,请向后兼容Android 2.3.3-2.3.7。
首先定义一个包含您的切换按钮的布局:
<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>
<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>
通过编程方式膨胀: 在您的活动或片段中,您可以执行以下操作:
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);
你可以使用 ActionBar.setCustomView()
方法并传递一个 Switch
或 ToggleButton
,但我不知道这是否会与其他 ActionBar 导航模式一起工作。至于保存此值,只需将其选中状态存储在 SharedPreferences 中,并在 Activity 创建时再次设置即可。
至于向后兼容性,你有两个选择:ActionBarSherlock 库或 Google 的新 v7 support library。
app:showAsAction="always"
和app:actionLayout="@layout/actionbar_service_toggle"
- 并声明app
命名空间为xmlns:app="http://schemas.android.com/apk/res-auto"
。 - ban-geoengineering