Reputation: 2187
Toggle button to change the background color of the layout of the Android app
I am trying to add a toggle button on the android studio that can change the background color of the app layout
public void perform_action(View v) {
g = (ToggleButton) findViewById(R.id.toggleButton);
g.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
RelativeLayout currentLayout = (RelativeLayout) findViewById(R.id.main_layout);
currentLayout.setBackgroundColor(Color.RED);
} else {
RelativeLayout currentLayout = (RelativeLayout) findViewById(R.id.main_layout);
currentLayout.setBackgroundColor(Color.BLACK);
}
}
});
}
the expected result is the background change however this is not happening and the app crashes after this
Upvotes: 0
Views: 491
Reputation: 2187
Once i changed to layout to Constraint it worked fine.
if (isChecked) {
ConstraintLayout currentLayout = (ConstraintLayout) findViewById(R.id.main_layout);
currentLayout.setBackgroundColor(Color.RED);
} else {
ConstraintLayout currentLayout = (ConstraintLayout) findViewById(R.id.main_layout);
currentLayout.setBackgroundColor(Color.BLACK);
Upvotes: 0
Reputation: 543
According to your crush
report: You are using ConstraintLayout
in the XML file. On the other hand, you are initializing RelativeLayout
in the Java file.
You have to use the same layout at the same time in both files. So change your XML file layout into RelativeLayout
Instead of ConstraintLayout
or change ConstraintLayout
in the Java file ConstraintLayout
of RelativeLayout.
Just keep in your mind Both Layouts should be the same.
Hope it will help you.
Thank you
Upvotes: 0
Reputation: 1432
please use Constraint layout here
RelativeLayout currentLayout = (RelativeLayout) findViewById(R.id.main_layout);
instead of RelativeLayout because you use constraint layout in your XML file ;)
Upvotes: 1