【问题标题】:How to change a specific Button's background color programmatically?如何以编程方式更改特定按钮的背景颜色?
【发布时间】:2021-09-27 18:35:51
【问题描述】:

我已经弄清楚了Theme 编辑器的基本知识,并为我感兴趣的Components 设置了基本值。

我在整个应用程序中使用ComponentSelectorComponents,所以我可以轻松选择任何Component

现在,我想在运行时更改特定Buttons 的背景颜色。最好的方法是什么?

【问题讨论】:

    标签: codenameone


    【解决方案1】:

    首先,对于新应用,您应该使用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

    【讨论】:

    • 我会试一试的。我假设.css文件是通过编辑器的“添加数据”菜单添加的。
    • 我已在 Codename One 设置中激活 css,但 IntelliJ 弹出一条消息,提示我需要 IntelliJ Ultimate 才能使用 css 文件。有解决办法吗?
    • 不,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中编辑样式。
    • 您可以将 CSS 与免费的 IntelliJ 一起使用,但您不会获得 CSS 的突出显示和代码完成,这很糟糕。我个人为 Ultimate 付费,这对我来说是值得的,但你可以在没有这些东西的情况下编辑代码,或者对 CSS 文件使用 VS Code。请注意,无论您使用哪种编辑器,动态编辑(因此在模拟器打开时样式会发生变化)都可以工作。如果你还在使用 Ant 需要先迁移到 maven,请看 maven 迁移工具的文章
    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 2014-12-21
    相关资源
    最近更新 更多