切换主题时有过渡效果。
// theme.kt
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
val CustomLight = CustomColor(textColor = Color.Black, bgColor = Color.White, btnShape = 10.dp)
val CustomDark = CustomColor(bgColor = Color.Black, textColor = Color.White, btnShape = 20.dp)
val LocalTheme = compositionLocalOf { CustomLight }
object CustomTheme {
val colors : CustomColor
@Composable
get() = LocalTheme.current //getter直接返回compositionLocal
enum class Themes {
LIGHT,DARK
}
}
@Stable
class CustomColor (textColor: Color, bgColor: Color, btnShape: Dp/*主题中设置圆角幅度*/) {
var textColor by mutableStateOf(textColor)
private set
var bgColor by mutableStateOf(bgColor)
private set
var btnShape by mutableStateOf(btnShape)
private set
}
@Composable
fun CustomThemeComponent(theme: CustomTheme.Themes = CustomTheme.Themes.LIGHT, content: @Composable () -> Unit){
val curTheme = when(theme) {
CustomTheme.Themes.LIGHT -> CustomLight
CustomTheme.Themes.DARK -> CustomDark
}
val bgColor by animateColorAsState(curTheme.bgColor, tween(1000), label = "")
val textColor by animateColorAsState(curTheme.textColor, tween(1000), label = "")
val btnShape by animateDpAsState(curTheme.btnShape, tween(1000), label = "")
val colors = CustomColor(textColor,bgColor, btnShape)
CompositionLocalProvider(LocalTheme provides colors) {
MaterialTheme(shapes = MaterialTheme.shapes, content = content)
}
}
//MainActivity.kt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
val theme by remember { mutableStateOf(CustomTheme.Themes.DARK) }
CustomThemeComponent(theme) {
Button(modifier = Modifier.padding(vertical = 150.dp),onClick = {
theme = when(theme) {
CustomTheme.Themes.LIGHT -> CustomTheme.Themes.DARK
CustomTheme.Themes.DARK -> CustomTheme.Themes.LIGHT
}
}) { Text(text = "切换") }
HomeScreen()
}
}
}
}
@Composable
fun HomeScreen() {
var i1 by rememberSaveable { mutableStateOf("") }
Column(modifier = Modifier.windowInsetsPadding(WindowInsets.systemBars).background(color = CustomTheme.colors.bgColor)) {
Text("首页", color = CustomTheme.colors.textColor, fontWeight = FontWeight.Bold)
TextField(value = i1, onValueChange = { i1 = it }, modifier = Modifier.clip(RoundedCornerShape(CustomTheme.colors.btnShape)))
Button(onClick = {
// nav.navigate("profile")
}) {
Text("跳转到个人中心")
}
}
}