Skip to content

Instantly share code, notes, and snippets.

@VitalyPeryatin
Created June 2, 2020 15:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VitalyPeryatin/9083dde7f13a6fa2181dcc3d978e3789 to your computer and use it in GitHub Desktop.
Save VitalyPeryatin/9083dde7f13a6fa2181dcc3d978e3789 to your computer and use it in GitHub Desktop.
Смена дневной/ночной темы
import android.content.res.Configuration
import android.os.Build
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import ru.dit.smartstaff.R
import ru.dit.smartstaff.repositories.AppThemeRepository
class AppThemeDelegate {
fun setAppTheme(activity: AppCompatActivity) {
val nightModeFlags = activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
val isDarkTheme = AppThemeRepository.isDarkTheme()
val currentMode = if (isDarkTheme) {
Configuration.UI_MODE_NIGHT_YES
} else {
Configuration.UI_MODE_NIGHT_NO
}
if (nightModeFlags != currentMode) {
val defaultNightMode = if (isDarkTheme) {
AppCompatDelegate.MODE_NIGHT_YES
} else {
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
activity.delegate.localNightMode = defaultNightMode
} else {
AppCompatDelegate.setDefaultNightMode(defaultNightMode)
}
}
updateStatusBarColor(activity)
}
fun setFollowSystemTheme(activity: AppCompatActivity) {
val defaultNightMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
activity.delegate.localNightMode = defaultNightMode
} else {
AppCompatDelegate.setDefaultNightMode(defaultNightMode)
}
updateStatusBarColor(activity)
}
fun updateStatusBarColor(activity: AppCompatActivity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
val mode = activity.resources?.configuration?.uiMode?.and(Configuration.UI_MODE_NIGHT_MASK)
val window = activity.window
window.statusBarColor = ContextCompat.getColor(activity, R.color.background)
when (mode) {
Configuration.UI_MODE_NIGHT_YES -> {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility and
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
}
Configuration.UI_MODE_NIGHT_NO -> {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment