1

I am working on a HarmonyOS project in that I wanted to set the background color of the component. In Android we have a function setBackgroundColor() in the View class, this can be done as shown below.

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

How can I set background color to a component in HarmonyOS?

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108

2 Answers2

1

@Gowtham GS's answer is correct. I'd like to add a little more:

You can also define the background color of the component when defining the component in the XML file. The attribute is background_element.

For example: ohos:background_element="white"

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

First you have to build an Element using some color,

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

later you have set the built element using setBackground API

    component.setBackground(buildElementByColor((Color.DKGRAY).getValue()));
Gowtham GS
  • 478
  • 2
  • 5