dimanche 27 janvier 2019

How to change the value of my CheckBox in another activity every time it's clicked

In my main activity there is a button and a textview. When the button is clicked, the textview is changed based on whether or not a checkbox is checked in my second activity. The way it is now, i have to close and reopen the app every time i click the checkbox if i want the changes to apply to my textview. how do i apply the changes every time the checkbox is clicked?

Below are examples of my codes.

My main activity code:

public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;

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

    button = findViewById(R.id.button);
    textView = findViewById(R.id.textView);


    SharedPreferences sharedPrefs = getSharedPreferences("com.company.aadne.sharedprefererences", MODE_PRIVATE);
    final Boolean state = sharedPrefs.getBoolean("checkBox1Key", false);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        if (state){
            textView.setText("Hello");
        }
        else{
            textView.setText("Goodbye");
        }
        }
    });

}

public void launchMain2Avtivity(View view) {
    Intent intent = new Intent(this, Main2Activity.class);
    startActivity(intent);
}

}

My second activity code:

public class Main2Activity extends AppCompatActivity {

private CheckBox checkBox1;

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

    checkBox1 = findViewById(R.id.checkBox1);

    SharedPreferences sharedPref = this.getSharedPreferences("com.company.aadne.sharedprefererences", MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPref.edit();
    editor.putBoolean("checkBox1", false);
    editor.commit();

    final boolean checkBox1Checked = sharedPref.getBoolean("checkBox1Key", false);
    checkBox1.setChecked(checkBox1Checked);

    checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editor.putBoolean("checkBox1Key", isChecked);
            editor.commit();
        }
    });

}

Thanks for any help!




Aucun commentaire:

Enregistrer un commentaire