javaandroidhuawei-mobile-serviceshuawei-developersharmonyos

How to load color resource using Resource ID in HarmonyOS?


I am building a HarmonyOS application and want to load color values that I have placed in the resources folder in resources/base/element/color.json. How can I load this color in my Java class?

In Android we can use the getColor() function for this:

context.getResources().getColor(R.color.colorID);

What is the alternative for this in HarmonyOS?


Solution

  • You may can refer to the following implementations:

    1. color.json
    {
    
      "color": [
    
        {
    
          "name": "primary",
    
          "value": "#FF0000"
    
        }
    
      ]
    
    }
    
    
    1. MainAbilitySlice
        public void onStart(Intent intent) {
    
            super.onStart(intent);
    
            super.setUIContent(ResourceTable.Layout_ability_main);
    
    
    
            ResourceManager resManager = this.getResourceManager();
    
            try {
    
                int color = resManager.getElement(ResourceTable.Color_primary).getColor();
    
                Text text = (Text) findComponentById(ResourceTable.Id_text_helloworld);
    
                text.setTextColor(new Color(color));
    
            } catch (IOException e) {
    
    
    
            } catch (NotExistException e) {
    
    
    
            } catch (WrongTypeException e) {
    
    
    
            }
    
        }