简体   繁体   中英

Get a checkbox variable from another activity in Android

I need some help getting a checkbox's state. Basically I want to get if a checkbox from an activity is checked then if it is, show some text on the main activity. I've read lots and lots of SO Q&As but nothing worked. I got this:

CheckBox show = (CheckBox) findViewById(R.id.checkBox);

public CheckBox getShow() {
    return show;
}

So I'd use

CheckBox setty = Settings.getCheck();

on the other class. But I get an error:

Cannot resolve method 'getCheck()'

How can I do this? I need to get if it's on or off and display it on the main activity. Remember that I can't use Intents because I won't have a button to transition, the text and value must be always there on the main class.

you can use shared preference to store a checkbox check/uncheck value..and based on that value you can show text in your other activity.

here is the code:

public static final String MyPREFERENCES = "MyPrefs";

initialize shared preference in onCreate() method of first activity

 sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
  CheckBox check1 = (CheckBox) view.findViewById(R.id.your_checkbox_id);

  //now initialize listener for checkbox

   check1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("checked", "1");
                    editor.commit();
                } else {
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("checked", "0");
                    editor.commit();
                }
            }
        });

Now in another activity you just have to load the shared preference data and show message based on condition

public void Load_checkbox() {
        //define MyPREFERENCES in other activity too- same as first activity
        SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 
        if (shared.getString("checked", "").equals("1")) {
             Toast.makeText(getApplicationContext(), "CheckBox Checked " ,Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getApplicationContext(), "CheckBox unchecked " ,Toast.LENGTH_LONG).show();
        }
    }

call this Load_checkbox() method in your second activity where u want to check the checkbox state of first activity

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