Search code examples
javaandroidhuawei-mobile-serviceshuawei-developersharmonyos

What is the alternative in Harmony OS for function setBackgroundColor() on View class in Android?


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?


Solution

  • 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()));