【发布时间】:2021-09-27 18:35:51
【问题描述】:
我已经弄清楚了Theme 编辑器的基本知识,并为我感兴趣的Components 设置了基本值。
我在整个应用程序中使用ComponentSelectorComponents,所以我可以轻松选择任何Component。
现在,我想在运行时更改特定Buttons 的背景颜色。最好的方法是什么?
【问题讨论】:
标签: codenameone
我已经弄清楚了Theme 编辑器的基本知识,并为我感兴趣的Components 设置了基本值。
我在整个应用程序中使用ComponentSelectorComponents,所以我可以轻松选择任何Component。
现在,我想在运行时更改特定Buttons 的背景颜色。最好的方法是什么?
【问题讨论】:
标签: codenameone
首先,对于新应用,您应该使用theme.css 文件而不是主题编辑器。
也就是说,在运行时使用ComponentSelector更改特定Buttons的背景颜色可以通过以下方式完成。
假设有一个 theme.css 包含:
#Constants {
includeNativeBool: true;
}
Button {
margin: 0.5mm;
padding: 0.5mm;
color: white;
border: none;
}
Button-Red {
cn1-derive: Button;
background-color: red;
}
Button-Green {
cn1-derive: Button;
background-color: green;
}
只有一个按钮的情况(注意我使用.asComponent()方法只选择一个组件,即使在这种情况下没有必要):
Form hi = new Form("Hi World", BoxLayout.y());
Button myBtn = new Button("My fun button", "Button-Red");
hi.add(FlowLayout.encloseCenter(myBtn));
hi.show();
UITimer.timer(2000, false, hi, () -> {
// this code changes the color of the button after two second
ComponentSelector.$("Button-Red").asComponent().setUIID("Button-Green");
hi.revalidate();
});
多个按钮的情况:
Form hi = new Form("Hi World", BoxLayout.y());
Button myBtn1 = new Button("My fun button 1", "Button-Red");
Button myBtn2 = new Button("My fun button 2", "Button-Red");
hi.add(FlowLayout.encloseCenter(myBtn1));
hi.add(FlowLayout.encloseCenter(myBtn2));
hi.show();
UITimer.timer(2000, false, hi, () -> {
// this code changes the color of the buttons after two second
ComponentSelector.$("Button-Red").setUIID("Button-Green");
hi.revalidate();
});
当然你可以用不同的方式来选择你感兴趣的组件,根据文档:https://www.codenameone.com/javadoc/com/codename1/ui/ComponentSelector.html
【讨论】:
theme.css 已经包含在每个 Codename One Maven 项目中并且它已经被激活。阅读这篇关于代号一的 Maven 结构的博文:codenameone.com/blog/maven-project-structure.html 如您所见,CSS 文件位于 common/src/main/css 中,项目默认设置为使用 CSS。您可以在common/src/main/css/theme.css中编辑样式。