First of all we will do a project in our android studio or where we want to use it.
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="130dp"
android:text="checkBox"
android:textColor="@color/purple_500"
android:textSize="20sp"
android:textStyle="bold" />
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Night Mode" />
</LinearLayout>
MainActivity
package com.example.darkmode;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
public class MainActivity extends AppCompatActivity {
private CheckBox checkBox;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setBackgroundDrawable(getDrawable(R.color.purple_700));
checkBox = findViewById(R.id.checkBox);
SharedPreferences sharedPreferences = getSharedPreferences("check", MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
checkBox.setChecked(sharedPreferences.getBoolean("checkBox", false));
final boolean isDarkMode = sharedPreferences.getBoolean("isDarkMode", false);
if (isDarkMode) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBox.isChecked()) {
if (isDarkMode) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
editor.putBoolean("isDarkMode", false);
editor.apply();
editor.putBoolean("checkBox", true);
editor.apply();
checkBox.setChecked(true);
}
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
editor.putBoolean("isDarkMode", true);
editor.apply();
editor.putBoolean("checkBox", false);
editor.apply();
checkBox.setChecked(false);
}
}
});
}
}
Thanks
0 Comments
Please do not enter any spam link in the comment box
Emoji