问题描述
我正在开发一个 HarmonyOS 库,我必须使用给定的布局来扩充布局 布局资源 id:int layoutRes 和 context:上下文上下文。
在android中,同样的事情是使用
val myAdapter = MyListingAdapter(myActivity)
//Setup the recyclerview
binding.myList.apply {
layoutManager = when {
columnCount <= 1 -> linearlayoutmanager(context)
else -> GridLayoutManager(context,columnCount)
}
myAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
val decoration =
DividerItemdecoration(myActivity,DividerItemdecoration.VERTICAL)
addItemdecoration(decoration)
setHasFixedSize(true)
adapter = myAdapter
}
lifecycleScope.launch {
viewmodel.getData().distinctUntilChanged().collectLatest { pagedData ->
myAdapter.submitData(pagedData)
}
}
安卓应用中的代码:
鸿蒙操作系统的替代方案是什么?
解决方法
LayoutInflater 的替代方案是 HarmonyOS 中的 LayoutScatter。用法如下
LayoutScatter.getInstance(context).parse(layoutRes,this,true);
,
您可以使用 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。