Android 中 View 类上的函数 setBackgroundColor() 在 Harmony Os 中的替代方法是什么?

问题描述

我正在处理 HarmonyOs 项目,因为我想设置组件的背景颜色。在 Android 中,我们在 View 类中有一个函数 setBackgroundColor(),这可以按如下所示完成。

View titleLayout = view.findViewById(R.id.titleLayout);
titleLayout.setBackgroundColor(calendarTitleBackgroundColor);

如何为 HarmonyOs 中的组件设置背景颜色?

解决方法

@Gowtham GS 的回答是正确的。我想补充一点:

您还可以在 XML 文件中定义组件时定义组件的背景颜色。属性为 background_element

例如:ohos:background_element="white"

,

首先你必须使用某种颜色构建一个元素,

    public static Element buildElementByColor(int color) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.RECTANGLE);
        drawable.setRgbColor(RgbColor.fromArgbInt(color));
        return drawable;
    }

稍后您使用 setBackground API 设置了构建元素

    component.setBackground(buildElementByColor((Color.DKGRAY).getValue()));