1

我正在实现一个自定义组件并尝试从 XML 中获取属性的输入。在 Android 中,它看起来像这样

<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"
   />

如何在 HarmonyOS 中做到这一点?

4

1 回答 1

0

第一步:需要在XML文件的根布局中自定义标签app(名称可自定义)。格式为: xmlns:app="http://schemas.huawei.com/res/ohos-auto",代码如下:

<?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>

步骤 2:当ArcPageIndicator在 XML 文件中使用时,定义行自定义属性apiArcOrientation。代码如下:

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

第三步:通过Java代码中的AttrSet获取属性值。代码如下:

public ArcPageIndicator(Context context, AttrSet attrSet) {
    ......
    String apiArcOrientation = attrSet.getAttr("apiArcOrientation").get().getStringValue();
}
于 2021-07-29T02:02:20.260 回答