package
com.example.nightmodebutton;
import
androidx.appcompat.app.AppCompatActivity;
import
androidx.appcompat.app.AppCompatDelegate;
import
android.os.Bundle;
import
android.widget.CompoundButton;
import
com.google.android.material.switchmaterial.SwitchMaterial;
import
java.util.Objects;
public
class
MainActivity
extends
AppCompatActivity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SwitchMaterial switchBtn = findViewById(R.id.switchBtn);
Objects.requireNonNull(getSupportActionBar ()).setTitle(
"LIGHT-NIGHT MODE SWITCH"
);
switchBtn.setOnCheckedChangeListener(
new
CompoundButton.OnCheckedChangeListener() {
@Override
public
void
onCheckedChanged (CompoundButton buttonView,
boolean
isChecked){
if
(isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
buttonView.setText(
"Night Mode"
);
}
else
{
AppCompatDelegate.setDefaultNightMode (AppCompatDelegate.MODE_NIGHT_NO);
buttonView.setText(
"Light Mode"
);
}
}
});
}
}