I have two images (not colors) called black
and white
. I've written this code so far:
public class MainActivity extends AppCompatActivity
{
View parentView;
SwitchCompat switchCompat;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchCompat = findViewById(R.id.switchCompat);
parentView = findViewById(R.id.parentView);
SharedPreferences prefs = getSharedPreferences("save", MODE_PRIVATE);
switchCompat.setChecked(prefs.getBoolean("value", false);
switchCompat.setOnClickListener(view -> {
if(switchCompat.isChecked()) {
parentView.setImageResource(R.drawable.black);
SharedPreferences.Editor ed = getSharedPreferences("save", MODE_PRIVATE);
ed.putBoolean("value", true);
ed.apply();
switchCompat.setChecked(true);
} else {
parentView.setImageResource(R.drawable.white);
SharedPreferences.Editor ed = getSharedPreferences("save", MODE_PRIVATE);
ed.putBoolean("value", false);
ed.apply();
switchCompat.setChecked(false);
}
});
}
Default background is white. As you see, if the user check switch on the background should be black, but this doesn't work. Do you know any solution?
CodePudding user response:
You needn't set the SwitchCompat if its changed, its redundant. Also SharedPreferences.Editor
was initialized wrong.
Try this
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
View parentView;
SwitchCompat switchCompat;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchCompat = findViewById(R.id.switchCompat);
parentView = findViewById(R.id.parentView);
prefs = getSharedPreferences("save", MODE_PRIVATE);
switchCompat.setChecked(prefs.getBoolean("value", false));
if (prefs.getBoolean("value", false)) {
parentView.setBackgroundResource(R.drawable.black);
} else {
parentView.setBackgroundResource(R.drawable.white);
}
switchCompat.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.getId() == R.id.switchCompat) {
if(isChecked) {
parentView.setImageResource(R.drawable.black);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("value", true);
ed.apply();
} else {
parentView.setImageResource(R.drawable.white);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("value", false);
ed.apply();
}
}
}
}