-
-
Save Smurph82/dddc908b2acd411a2b8f5bd8b5549c09 to your computer and use it in GitHub Desktop.
Night Mode inflater
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
/* | |
* Copyright 2017 Google, Inc. | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
import android.content.Context | |
import android.content.res.Configuration | |
import android.support.annotation.LayoutRes | |
import android.view.ContextThemeWrapper | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
fun inflateNightModeView( | |
context: Context, | |
@LayoutRes layoutId: Int, | |
container: ViewGroup?, | |
isNightMode: Boolean): View { | |
val context = ContextThemeWrapper( | |
createNightModeContext(context, isNightMode), | |
R.style.Theme_AppCompat_DayNight) // This should point to your theme | |
return LayoutInflater.from(context).inflate(layoutId, container, false) | |
} | |
fun createNightModeContext(context: Context, isNightMode: Boolean): Context { | |
val uiModeFlag = if (isNightMode) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO | |
val config = Configuration(context.resources.configuration) | |
config.uiMode = uiModeFlag or (config.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) | |
return context.createConfigurationContext(config) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment