如何保存广播组的状态?

时间:2019-03-07 13:53:07

标签: java android android-radiogroup

我希望用户选中与他相同的单选按钮 在关闭应用程序之前进行过检查。

这是我的源代码

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;

public class MainActivity extends AppCompatActivity {

    RadioGroup radioGroup;
    RadioButton radioButton;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        radioGroup = findViewById(R.id.radioGroup);
        textView = findViewById(R.id.text_view_selected);

        Button buttonApply = findViewById(R.id.button_apply);
        buttonApply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int radioId = radioGroup.getCheckedRadioButtonId();

                radioButton = findViewById(radioId);

                textView.setText("Your choice: " + radioButton.getText());
            }
        });
    }

    public void checkButton(View v) {
        int radioId = radioGroup.getCheckedRadioButtonId();

        radioButton = findViewById(radioId);

        Toast.makeText(this, "Selected Radio Button: " + radioButton.getText(),
                Toast.LENGTH_SHORT).show();

    }
}

我希望单选按钮状态在下次应用程序时被保存 使用。

1 个答案:

答案 0 :(得分:0)

您应该看看classpath 'com.android.tools.build:gradle:3.3.2'https://developer.android.com/training/data-storage/shared-preferences

保存数据:

sharedPreferences

检索数据:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("myRadio", radioButton.getText());
editor.commit();

目前,您可以执行以下操作:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "";
String radioButtonText = sharedPref.getString("myRadio", defaultValue);

最佳