想了解更多內容,請訪問:
51CTO和華為官方戰略合作共建的鴻蒙技術社區
https://harmonyos.51cto.com/#zz
harmony-view-binding
最新版本:Gitee倉庫查看
是什麼?
- view-binding for harmony
- 鴻蒙應用開發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. 執行gradle sync 即可自動生成ViewBinding類,生成目錄在feature中的build/generated/source/viewBinding中,
類的命名方法通過獲得xml布局文件名後遵循大駝峰法(Upper Camel Case)並追加Binding後綴,如:MainAbilityBinding
4. 在需要填充布局的地方使用
主要是兩個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); } }
可選項
1. 提供設置根布局api
parse(Context context, ComponentContainer parent, boolean attachToRoot)
2. 支持feature模塊view-binding功能的開啟與關閉:
feature中的build.gradle中設置
viewBinding{ enable false // false為關閉,插件將不會解析該feature所有的xml布局文件, //true為開啟,插件將會解析該feature下所有的xml布局文件 }
3. 支持針對單個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"> ... </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
©著作權歸作者和HarmonyOS技術社區共同所有,如需轉載,請註明出處,否則將追究法律責任.
想了解更多內容,請訪問:
51CTO和華為官方戰略合作共建的鴻蒙技術社區
https://harmonyos.51cto.com/#zz
【編輯推薦】
點讚 0