Search code examples
javaandroidhuawei-mobile-serviceshuawei-developersharmonyos

How to create custom attributes for a custom component that can be assigned from XML in HarmonyOS?


I am implementing a custom component and trying to take input from XML for an attribute. In Android, it looks something like this

<it.beppi.arcpageindicator.ArcPageIndicator
   android:layout_width="100dp"
   android:layout_height="20dp"
   android:layout_alignParentTop="true"
   android:layout_centerHorizontal="true"
   app:apiViewPager="@id/view_pager"
   app:apiArcOrientation="toDown"
   app:apiAnimationType="cover"
   />

How can I do this in HarmonyOS?


Solution

  • Step 1: You need to customize the label app (the name can be customized) in the root layout of the XML file. The format is: xmlns:app="http://schemas.huawei.com/res/ohos-auto",and the code is as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <DirectionalLayout
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        xmlns:app="http://schemas.huawei.com/res/ohos-auto"
        ......
        >
    </DirectionalLayout>
    

    Step 2: When ArcPageIndicator is used in the XML file, define the line custom attribute apiArcOrientation. The code is as follows:

    <!--com.huawei.flowlayout.library is the package path of the FlowLayout class ---->
    <com.huawei.flowlayout.library.FlowLayout
        ......
        app:apiArcOrientation="toDown"
        />
    

    Step 3: Obtain the attribute value through AttrSet in the Java code. The code is as follows:

    public ArcPageIndicator(Context context, AttrSet attrSet) {
        ......
        String apiArcOrientation = attrSet.getAttr("apiArcOrientation").get().getStringValue();
    }