首页 > 技术知识 > 正文

Harmony-view-binding 最新版本请到 Gitee 仓库查看: https://gitee.com/jeffer_s/harmony-view-binding

是什么?

view-binding for harmony

鸿蒙应用开发 view-binding 插件,消除 findComponentById 模版代码

无注解、编译期间生成 Binding 类文件

怎么用?

①在 project 根目录的 build.gradle 文件中引入 view-binding 的 maven 仓库地址和 classpath。

buildscript { repositories { maven { url https://mirrors.huaweicloud.com/repository/maven/ } maven { url https://developer.huawei.com/repo/ }

jcenter() maven{ url https://dl.bintray.com/eholee/maven } } dependencies { classpath com.huawei.ohos:hap:2.4.0.1 // view-binding classpath com.eholee.plugin:view-binding:1.0.1 }

}

②在 feature 模块的 build.gradle 文件中引入 view-binding 插件。

apply plugin: com.huawei.ohos.hap apply plugin: com.eholee.plugin.view-binding ohos { … } viewBinding{ enable true } dependencies { … }

③执行 gradle sync 即可自动生成 ViewBinding 类,生成目录在 feature 中的 build/generated/source/viewBinding 中。

类的命名方法通过获得 xml 布局文件名后遵循大驼峰法(Upper Camel Case)并追加 Binding 后缀,如:MainAbilityBinding。

④在需要填充布局的地方使用。

主要是两个 api: binding = AbilityMainBinding.parse(this)

binding.getRoot() public class MainAbilitySlice extends AbilitySlice { private AbilityMainBinding binding; @Override public void onStart(Intent intent) { super.onStart(intent); binding = AbilityMainBinding.parse(this); super.setUIContent(binding.getRoot()); binding.textHelloworld.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { new ToastDialog(MainAbilitySlice.this).setText(“click”).show(); } }); }

@Override public void onActive() { super.onActive(); } @Override public void onForeground(Intent intent) { super.onForeground(intent); }

}

可选项

①提供设置根布局 api

parse(Context context, ComponentContainer parent, boolean attachToRoot)

②支持 feature 模块 view-binding 功能的开启与关闭

feature 中的 build.gradle 中设置: viewBinding{ enable false // false为关闭,插件将不会解析该feature所有的xml布局文件, //true为开启,插件将会解析该feature下所有的xml布局文件 }

③支持针对单个 xml 布局文件开启与关闭 view-binding 功能

默认是都开启,如需关闭,需在 xml 根节点中加入如下信息:

xmlns:eholee=”http://schemas.eholee.com/viewbinding” eholee:view_binding=”false” 示例: <?xml version=”1.0″ encoding=”utf-8″?> <DirectionalLayout xmlns:ohos=”http://schemas.huawei.com/res/ohos” xmlns:eholee=”http://schemas.eholee.com/viewbinding” eholee:view_binding=”false” ohos:height=”match_parent” ohos:width=”match_parent” ohos:background_element=”$color:colorAppBackground” ohos:orientation=”vertical”> …

Gitee 仓库地址:

https://gitee.com/jeffer_s/harmony-view-binding

来源:鸿蒙技术社区

猜你喜欢