编程语言
首页 > 编程语言> > 如何在整个Android应用程序中保存rediobutton的状态?

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

作者:互联网

我有两个单选组,每个组有两个单选按钮.
每个组中的第一个单选按钮的默认值为true(即选中).
当用户单击任何单选按钮时,以及当用户从其他活动中恢复时,在这些单选按钮组/单选按钮上所做的选择都将消失.
如何保存/恢复单选/单选按钮的选择状态?
这是我的Java代码.

        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,radio-button
来源: https://codeday.me/bug/20191202/2084949.html