Created
August 8, 2020 20:23
-
-
Save kolanse/7ef19cad3f6f51986a74d38c27885554 to your computer and use it in GitHub Desktop.
dark mode kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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