import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
public class MainActivity extends AppCompatActivity {
Switch change_background;
@SuppressLint("ResourceAsColor")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout
background=
(LinearLayout)findViewById(R.id.background);
change_background=
(Switch)findViewById(R.id.switch_button);
change_background.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton
buttonView, boolean isChecked) {
if(isChecked){
background.setBackgroundColor(R.color.black);
change_background.setTrackResource(R.color.blue);
change_background.setThumbResource(R.color.white); }
else {
background.setBackgroundColor(R.color.white);
change_background.setThumbResource(R.color.black);
change_background.setTrackResource(R.color.blue);
}
}
});}}
I used a Linear Layout as the root view of this project,My intention was to change the background of the app and change the thumb and track of the switch when the switch is checked and do the same thing with different colors when the switch is unchecked. But after running the app, when i check the switch widget, the app malfunctions and switch widget goes invisible and nothing works as i intended
note:) Ignore my useless imports
setBackgroundColor
takes parameter @ColorInt
not @ColorRes
you should change it to
background.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.bg_white));
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.