Created
June 2, 2020 15:04
-
-
Save VitalyPeryatin/9083dde7f13a6fa2181dcc3d978e3789 to your computer and use it in GitHub Desktop.
Смена дневной/ночной темы
This file contains 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
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