session-android/app/src/main/java/org/thoughtcrime/securesms/util/UiModeUtilities.kt

65 lines
2.3 KiB
Kotlin
Raw Normal View History

2021-07-09 05:18:48 +02:00
package org.thoughtcrime.securesms.util
2020-08-27 06:38:25 +02:00
import android.content.Context
import android.content.res.Configuration
import androidx.annotation.StringRes
2020-08-27 06:38:25 +02:00
import androidx.appcompat.app.AppCompatDelegate
import androidx.preference.PreferenceManager
import network.loki.messenger.R
2020-08-27 06:38:25 +02:00
/**
* Day/night UI mode related utilities.
* @see <a href="https://developer.android.com/guide/topics/ui/look-and-feel/darktheme">Official Documentation</a>
*/
object UiModeUtilities {
private const val PREF_KEY_SELECTED_UI_MODE = "SELECTED_UI_MODE"
@JvmStatic
fun setUserSelectedUiMode(context: Context, uiMode: UiMode) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
2020-08-27 06:38:25 +02:00
prefs.edit()
.putString(PREF_KEY_SELECTED_UI_MODE, uiMode.name)
.apply()
AppCompatDelegate.setDefaultNightMode(uiMode.nightModeValue)
}
@JvmStatic
fun getUserSelectedUiMode(context: Context): UiMode {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
2020-08-27 06:38:25 +02:00
val selectedUiModeName = prefs.getString(PREF_KEY_SELECTED_UI_MODE, UiMode.SYSTEM_DEFAULT.name)!!
var selectedUiMode: UiMode
try {
selectedUiMode = UiMode.valueOf(selectedUiModeName)
} catch (e: IllegalArgumentException) {
// Cannot recognize UiMode constant from the given string.
selectedUiMode = UiMode.SYSTEM_DEFAULT
}
return selectedUiMode
}
@JvmStatic
fun setupUiModeToUserSelected(context: Context) {
2020-08-27 06:38:25 +02:00
val selectedUiMode = getUserSelectedUiMode(context)
setUserSelectedUiMode(context, selectedUiMode)
}
/**
* Whether the application UI is in the light mode
* (do not confuse with the user selected UiMode).
*/
@JvmStatic
fun isDayUiMode(context: Context): Boolean {
val uiModeNightBit = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
return uiModeNightBit == Configuration.UI_MODE_NIGHT_NO
}
2020-08-27 06:38:25 +02:00
}
enum class UiMode(
@StringRes
val displayNameRes: Int,
2020-08-27 06:38:25 +02:00
val nightModeValue: Int) {
DAY(R.string.dialog_ui_mode_option_day, AppCompatDelegate.MODE_NIGHT_NO),
NIGHT(R.string.dialog_ui_mode_option_night, AppCompatDelegate.MODE_NIGHT_YES),
SYSTEM_DEFAULT(R.string.dialog_ui_mode_option_system_default, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
2020-08-27 06:38:25 +02:00
}