1

I am working on a HarmonyOS library where I have to inflate a layout with a given layout resource id: int layoutRes and context: Context context.

In android, the same thing is done using

LayoutInflater.from(context).inflate(layoutRes, this, true);

code in android app:

enter image description here

What is the alternative for HarmonyOS?

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108

2 Answers2

2

Alternative for LayoutInflater is LayoutScatter in HarmonyOS. Usage is as follows

LayoutScatter.getInstance(context).parse(layoutRes, this, true);
Gowtham GS
  • 478
  • 2
  • 5
2

You can use LayoutScatter.getInstance(Context context).parse(int xmlId, ComponentContainer root, boolean attachToRoot) to implement this.

The following is the sample code for your reference:

<DirectionalLayout

    ohos:id="$+id:root_dir_layout"

    xmlns:ohos="http://schemas.huawei.com/res/ohos"

    ohos:height="match_parent"

    ohos:width="match_parent"

    ohos:orientation="vertical"
    >
</DirectionalLayout>


private void initView() {

    if (findComponentById(ResourceTable.Id_root_dir_layout)!= null &&

        findComponentById(ResourceTable.Id_root_dir_layout) instanceof DirectionalLayout) {

        rootDirectionalLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_root_dir_layout);

        DirectionalLayout contentComponent = (DirectionalLayout) LayoutScatter.getInstance(

                getContext()).parse(ResourceTable.Layout_dialog_delete, null, false);

        rootDirectionalLayout.addComponent(contentComponent);

    }

}

For more details, pls kindly refer to Docs.

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108