如何在其他活动中设置单选按钮默认选中?

How to set radio button checked default in other activities?

我想设置单选按钮在登录 activity 时默认选中,因为用户当时登录时活动按钮设置自动选中,当用户进入设置 activity 然后更改单选按钮button selection 在设置 activity 中将按钮的选择保存为用户 select .

代码:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       //  String radiodefault=R.id.Active;
        @Override

        public void onCheckedChanged(RadioGroup group, int checkedId) {

            // find which radio button is selected

            if(checkedId == R.id.Active) {

                Toast.makeText(getApplicationContext(), "choice: Active",

                        Toast.LENGTH_SHORT).show();
            }

            else if (checkedId == R.id.Inactive)
            {
                Toast.makeText(getApplicationContext(), "choice: Inactive",

                        Toast.LENGTH_SHORT).show();

            }
        }



    });
    active = (RadioButton) findViewById(R.id.Active);

    inactive = (RadioButton) findViewById(R.id.Inactive);

    button = (Button)findViewById(R.id.chooseBtn);

    button.setOnClickListener(new View.OnClickListener() {



        @Override

        public void onClick(View v) {

            int selectedId = radioGroup.getCheckedRadioButtonId();



            // find which radioButton is checked by id

            if(selectedId == active.getId()) {

                Toast.makeText(Settings.this,"Active is selected",Toast.LENGTH_LONG).show();

            }
            else if(selectedId == inactive.getId())
            {

                Toast.makeText(Settings.this,"Inactive is selected",Toast.LENGTH_LONG).show();

您可以使用 SharedPreference 来存储 CheckBox 的值,然后在 activity 重新启动时再次加载它。

SharedPreferences preferences = getSharedPreferences("checkBox",MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("Active",active.isChecked());
        editor.putBoolean("InActive",inactive.isChecked());
        editor.apply();

然后在加载 activity 时将其检索为:

boolean isActive = preferences.getBoolean("Active",false);
boolean isInActvie = preferences.getBoolean("InActive",false);

然后您可以设置 CheckBox 的当前状态,例如:

active.setChecked(isActive);
inactive.setChecked(isInActive);

使用 SharedPreference 将勾选存储为默认值