Android 中操作栏中的切换按钮

5

有没有办法将ToggleButton放在ActionBar中,并让它保存其状态,这样当您再次打开相同的活动时,它的状态与您离开时相同?

附加: 如果可能的话,请向后兼容Android 2.3.3-2.3.7。

2个回答

2

首先定义一个包含您的切换按钮的布局

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

然后你有两种选择继续操作:
使用动作布局: 注意:请保留HTML标签。
<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);

为了使其正常工作,我必须使用 app:showAsAction="always"app:actionLayout="@layout/actionbar_service_toggle" - 并声明 app 命名空间为 xmlns:app="http://schemas.android.com/apk/res-auto" - ban-geoengineering

0

你可以使用 ActionBar.setCustomView() 方法并传递一个 SwitchToggleButton,但我不知道这是否会与其他 ActionBar 导航模式一起工作。至于保存此值,只需将其选中状态存储在 SharedPreferences 中,并在 Activity 创建时再次设置即可。

至于向后兼容性,你有两个选择:ActionBarSherlock 库或 Google 的新 v7 support library


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接