applibgroup / HarmonyOS-Knowledgebase

This repository contains code samples of HarmonyOS Training
Apache License 2.0
17 stars 6 forks source link

What is the alternative in Harmony Os for TypedArray in Android? #30

Closed chakrichokkaku closed 3 years ago

chakrichokkaku commented 3 years ago

In my project I want to retrieve the color value for the custom attributes at index. Like in android we have the TypedArray to do this functionality.

final TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CustomCalendarView, 0, 0);
calendarBackgroundColor = typedArray.getColor(R.styleable.CustomCalendarView_calendarBackgroundColor, getResources().getColor(R.color.white));
calendarTitleBackgroundColor = typedArray.getColor(R.styleable.CustomCalendarView_titleLayoutBackgroundColor, getResources().getColor(R.color.white));
calendarTitleTextColor = typedArray.getColor(R.styleable.CustomCalendarView_calendarTitleTextColor, getResources().getColor(R.color.black));
weekLayoutBackgroundColor = typedArray.getColor(R.styleable.CustomCalendarView_weekLayoutBackgroundColor, getResources().getColor(R.color.white));
typedArray.recycle();

So we don't have TypedArray in Harmony OS. What is the way of doing this functionality?

Link to StackOverflow https://stackoverflow.com/questions/68587340/what-is-the-alternative-in-harmony-os-for-typedarray-in-android

Additional information Developer Platform: Windows DevEco Studio version: 2.1.0.303 SDK API version: 5 SDK version: 2.1.1.21 Device: Not required Device OS version: Not required

GowthamRayar commented 3 years ago

You don't need TypedArray to retrieve custom attributes from AttributeSet in HarmonyOS, instead AttrSet API directly allows you to retrieve custom attributes.

    indicatorNormalColor = mAttrSet.getAttr(INDICATOR_NORMAL_COLOR).isPresent() ?
            mAttrSet.getAttr(INDICATOR_NORMAL_COLOR).get().getColorValue() : defaultIndicatorNormalColor;
    indicatorSelectedColor = mAttrSet.getAttr(INDICATOR_SELECTED_COLOR).isPresent() ?
            mAttrSet.getAttr(INDICATOR_SELECTED_COLOR).get().getColorValue() : defaultIndicatorSelectedColor;
    indicatorStrokeColor = mAttrSet.getAttr(INDICATOR_STROKE_COLOR).isPresent() ?
            mAttrSet.getAttr(INDICATOR_STROKE_COLOR).get().getColorValue() : defaultIndicatorStrokeColor;
    indicatorNormalStrokeWidth = mAttrSet.getAttr(INDICATOR_NORMAL_STROKE_WIDTH).isPresent() ?
            mAttrSet.getAttr(INDICATOR_NORMAL_STROKE_WIDTH).get().getDimensionValue() : defaultIndicatorNormalStrokeWidth;
    indicatorSelectedStrokeWidth = mAttrSet.getAttr(INDICATOR_SELECTED_STROKE_WIDTH).isPresent() ?
            mAttrSet.getAttr(INDICATOR_SELECTED_STROKE_WIDTH).get().getDimensionValue() :