鴻蒙Harmony應(yīng)用開發(fā)view-binding插件,和findComponentById說再見
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz
harmony-view-binding
最新版本:Gitee倉庫查看
是什么?
- view-binding for harmony
- 鴻蒙應(yīng)用開發(fā)view-binding插件,消除findComponentById模版代碼
- 無注解、編譯期間生成Binding類文件
怎么用?
1. 在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'
- }
- }
2. 在feature模塊的build.gradle文件中引入view-binding插件
- apply plugin: 'com.huawei.ohos.hap'
- apply plugin: 'com.eholee.plugin.view-binding'
- ohos {
- ...
- }
- viewBinding{
- enable true
- }
- dependencies {
- ...
- }
3. 執(zhí)行g(shù)radle sync 即可自動(dòng)生成ViewBinding類,生成目錄在feature中的build/generated/source/viewBinding中,
類的命名方法通過獲得xml布局文件名后遵循大駝峰法(Upper Camel Case)并追加Binding后綴,如:MainAbilityBinding
4. 在需要填充布局的地方使用
主要是兩個(gè)api:1. binding = AbilityMainBinding.parse(this); 2. 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);
- }
- }
可選項(xiàng)
1. 提供設(shè)置根布局api
- parse(Context context, ComponentContainer parent, boolean attachToRoot)
2. 支持feature模塊view-binding功能的開啟與關(guān)閉:
feature中的build.gradle中設(shè)置
- viewBinding{
- enable false
- // false為關(guān)閉,插件將不會(huì)解析該feature所有的xml布局文件,
- //true為開啟,插件將會(huì)解析該feature下所有的xml布局文件
- }
3. 支持針對(duì)單個(gè)xml布局文件開啟與關(guān)閉view-binding功能
默認(rèn)是都開啟,如需關(guān)閉,需在xml根節(jié)點(diǎn)中加入如下信息:
- 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">
- ...
- </DirectionalLayout>
Gitee倉庫地址:https://gitee.com/jeffer_s/harmony-view-binding
參考
1. Android ViewBinding
2. com.huawei.ohos:hap:2.4.0.1 插件api
LICENSE
Apache License 2.0
©著作權(quán)歸作者和HarmonyOS技術(shù)社區(qū)共同所有,如需轉(zhuǎn)載,請(qǐng)注明出處,否則將追究法律責(zé)任.
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz