applibgroup / HarmonyOS-Knowledgebase

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

What is the HarmonyOS alternative for android.content.res.TypedArray? #38

Closed HaritJaiswal closed 3 years ago

HaritJaiswal commented 3 years ago

Describe the query

Android uses TypedArray as a container for attribute values. Here is an example:

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.EmojiReactionView);

where attrs is an android.util.AttributeSet object. The project has an XML file which contains many attributes with <attr> tag. AttributeSet is a collection of those attributes. Now TypedArray has a lot of useful functions to get information about attributes (See here). Basically, I want to perform functions, similar to the ones given in the link, on the attributes.

How to do so in HarmonyOS?

Create the query with harmonyos tag in stackoverflow and share the link here:

**** https://stackoverflow.com/questions/68588696/what-is-the-harmonyos-alternative-for-android-content-res-typedarray

Additional information

Developer Platform: Windows DevEco Studio version: 2.1.0.501 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() :