我正在开发一个 HarmonyOS 库,我必须在其中使用给定的布局资源 id:int layoutRes 和 context:Context context 来扩展布局。
在android中,同样的事情是使用
LayoutInflater.from(context).inflate(layoutRes, this, true);
安卓应用中的代码:
HarmonyOS 的替代品是什么?
我正在开发一个 HarmonyOS 库,我必须在其中使用给定的布局资源 id:int layoutRes 和 context:Context context 来扩展布局。
在android中,同样的事情是使用
LayoutInflater.from(context).inflate(layoutRes, this, true);
安卓应用中的代码:
HarmonyOS 的替代品是什么?
您可以使用它LayoutScatter.getInstance(Context context).parse(int xmlId, ComponentContainer root, boolean attachToRoot)
来实现这一点。
以下是示例代码供您参考:
<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);
}
}
有关更多详细信息,请参阅Docs。
LayoutInflater的替代方案是HarmonyOS中的 LayoutScatter。用法如下
LayoutScatter.getInstance(context).parse(layoutRes, this, true);