因此,在当前的andriod开发中,如果我们需要引用主题中的颜色集,我们可以简单地执行以下操作:(在xml布局中)
....
<TextView
...
android:textColor="?attr/colorPrimary"
.../>
....
如果我将主题设置为蓝色。我将在上面的文本视图中获得该颜色。
我想知道如何在Jetpack Compose
中做同样的事情。在Compose
中,我们这样做,
MaterialTheme(...) {
Column {
Text(
...
textStyle = TextStyle(color = ????) // How to I reference to the theme?
)
}
}
答案 0 :(得分:3)
您可以使用类似的内容:
import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";
class App extends Component {
constructor() {
super();
this.state = {
notifications: [
{
from: { id: 0, name: "Quentin" },
message: ["Message 1"]
},
{
from: { id: 1, name: "John" },
message: ["Message 1"]
},
{
from: { id: 2, name: "Henry" },
message: ["Message 1"]
}
]
};
this.pushMessage = this.pushMessage.bind(this);
}
pushMessage (id, message) {
const newState = Object.assign([], this.state);
newState.notifications.forEach(notif => {
if (notif.from.id === id) {
notif.message.push(message);
}
});
this.setState(newState, () => console.log(this.state));
};
render() {
return (
<div>
<button onClick={() => this.pushMessage(1, "Hello World")}>
Push message
</button>
</div>
);
}
}
render(<App />, document.getElementById("root"));
答案 1 :(得分:1)
撰写根据材料颜色规范提供ColorPalette
来生成您的应用主题。它提供lightColorPalette
和darkColorPalette
分别定义明暗模式的主题。
val lightThemeColors = lightColorPalette(
primary = Color(0xFFFFFFFF),
primaryVariant = Color(0xFFFFFFFF),
onPrimary = Color.Black,
secondary = Color.Transparent,
onSecondary = Color.White,
background = Color.White,
onBackground = Color(0xFF212121),
surface = Color.White,
onSurface = Color(0xFF212121),
error = Color.Red,
onError = Color.White
)
val darkThemeColors = darkColorPalette(
primary = Color(0xFF000000),
primaryVariant = Color(0xFF000000),
onPrimary = Color.White,
secondary = Color.White,
onSecondary = Color.White,
surface = Color(0xFF212121),
background = Color(0xFF212121),
onBackground = Color.White,
onSurface = Color.White,
error = Color.Red,
onError = Color.White
)
MaterialTheme(
colors = if(isSystemInDarkTheme()) darkThemeColors else lightThemeColors
) {
Column {
Text(
textStyle = TextStyle(color = MaterialTheme.colors.primary)
)
}
}
如果您想为主题添加更多自定义颜色,则可以将ColorPalette
与扩展变量一起使用,如下所示
@Composable
val ColorPalette.myColor: Color
get() = if(!isLight) Color(0xFF424242) else Color.White
现在,您可以使用MaterialTheme.colors.myColor
进行添加了。
如果您要包含android colors xml中的颜色,则可以使用colorResource(id = R.color.anyName)
函数。