简体   繁体   中英

How to set radio button checked default in other activities?

I want to set radio button checked by default in Log in activity as user log in at that time active button sets checked automatically and when user goes to setting activity and then changes the radio button selection at that time it saves the choice of button as user select in setting activity .

Code:

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();

You can use SharedPreference to store the value of the CheckBox and then load it again when activity is relaunched.

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

And then when loading the activity retrieve it as:

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

You can then set the current state of the CheckBox like:

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

使用SharedPreference将检查的内容存储为默认值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM