android - 如何在android中的整个应用程序中保存rediobutton的状态?

标签 android radio-button

我有两个单选组,每个组都有两个单选按钮。 每个组中第一个单选按钮的默认值为 true(即 checked )。 当用户点击任何单选按钮以及当用户从其他 Activity 中回来时,在这些单选组/单选按钮上所做的选择都消失了...... 如何保存/恢复单选组/单选按钮选择状态?? 这是我的 java 代码..对于一个 radio 组..

        final RadioButton radioOn = ( RadioButton )findViewById(
        R.id.rbOn );
    final RadioButton radioOff = ( RadioButton )findViewById(
        R.id.rbOff );
    radioOn.setChecked( true );
    radioOn.setOnClickListener( auto_lock_on_listener );
    radioOff.setOnClickListener( auto_lock_off_listener );

请帮忙。

最佳答案

您需要覆盖 onSaveInstanceState(Bundle savedInstanceState) 并将要更改的应用程序状态值写入 Bundle 参数,如下所示:

@Override

    public void onSaveInstanceState(Bundle savedInstanceState) {
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
      savedInstanceState.putBoolean("MyBoolean", true);
      savedInstanceState.putDouble("myDouble", 1.9);
      savedInstanceState.putInt("MyInt", 1);
      savedInstanceState.putString("MyString", "Welcome back to Android");
      // etc.
      super.onSaveInstanceState(savedInstanceState);
    }

Bundle 本质上是一种存储 NVP(“名称-值对”)映射的方法,它将被传递到 onCreate 和 onRestoreInstanceState,您可以在其中提取值,如下所示:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}

您通常会使用此技术来存储应用程序的实例值(选择、未保存的文本等)。

关于android - 如何在android中的整个应用程序中保存rediobutton的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8486914/

相关文章:

Android单选按钮取消选中

html - 如何在 Firefox 和 IE 中使用键盘导航跳过隐藏的单选选项?

javascript - 单选按钮选择动态更改其他单选按钮值

android - 如何在 "query"方法中传递两个或多个选择参数

java - 在android中,如何从图像按钮中提取图像?

java - IndexedDB 在 Android 原生应用中工作

java - Java 中的自动换行单选按钮文本?

android - 字幕 TextView 动画

android - 为什么我的 CheckedTextView 图标跳转到我的 GridView 中的不同元素?

javascript - 通过 JavaScript 验证单选按钮