Skip to content

Instantly share code, notes, and snippets.

@kolanse
Created August 8, 2020 20:23
Show Gist options
  • Save kolanse/7ef19cad3f6f51986a74d38c27885554 to your computer and use it in GitHub Desktop.
Save kolanse/7ef19cad3f6f51986a74d38c27885554 to your computer and use it in GitHub Desktop.
dark mode kotlin
package com.example.constrainttutorial
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatDelegate
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/**
* save the settings of the dark mode by using shared preferences
*/
val appSettingsPref: SharedPreferences = getSharedPreferences("appSettings", 0)
val isNightMode: Boolean = appSettingsPref.getBoolean("NightMode", false)
val sharedPrefEdit: SharedPreferences.Editor = appSettingsPref.edit()
/**
* check whether isNightMode is true. if it is enable dark mode else disable it
*/
if (isNightMode){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
var buttonMode = findViewById<Button>(R.id.mode_button)
/**
* When the button is clicked if night mode is true disable it and put the value in our shared preferences
*/
buttonMode.setOnClickListener {
if (isNightMode){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
sharedPrefEdit.putBoolean("NightMode", false).apply()
} else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
sharedPrefEdit.putBoolean("NightMode", true).apply()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment