当前位置: 首页 > 科技观察

HarmonyOS三方软件开发指南(18)-Flexbox流式布局组件

时间:2023-03-13 20:38:04 科技观察

更多内容请访问:Harmonyos技术社区https://harmonyos.51cto.com,与华为官方共同打造,我来介绍一下用法以及底部导航栏组件的开发指南。本文将为大家带来鸿蒙三方组件的另一种实现方式:Flexbox。什么是弹性盒?如果熟悉Java的Swing,就不会陌生。ViewGroup的宽度自动加到右边,如果当前行剩余空间不足,自动加到下一行。感觉所有控件都向左浮动。当第一行满了就飘到第二行~所以也叫流式布局。鸿蒙没有提供流体布局,但是在某些场合,流体布局还是很适合使用的,比如关键词标签,搜索热词榜等,比如下图:这些特别适合使用Flexbox,本文将指导大家自己实现Flexbox,然后使用我们自己定义的Flexbox来实现上面的标签效果。学会使用控件,学会写控件,相信大家都明白,授人以鱼不如授人以渔。接下来我们来看看鸿蒙模拟器的实现效果。效果图如下:图(1)默认标签状态图(2)标签选择状态VideoCache使用指南?新建项目,添加组件Har包依赖在应用模块中添加HAR,只需要复制flexboxlibrary-debug.har到entry\libs目录。?修改配置文件1、在布局中添加如下代码:="灰色"ohos:orientation="垂直"/>2。在代码中使用如下方式://mNames为item的数据源,可以是任何需要显示的显示根据实际情况,定义parentLayout=(HWFlowViewGroup)findComponentById(ResourceTable.Id_viewgroup);parentLayout.HWFlowViewGroup(getContext(),mNames,parentLayout);parentLayout.setOnItemClickListener((Componentview)->{//item点击后回调Texttext=(Text)view;if(text.isSelected()){text.setTextColor(Color.黑色);}else{text.setTextColor(Color.WHITE);}});1.VideoCache开发指南上面已经说明了Flexbox在开发过程中是如何使用的,接下来简单分析一下Flexbox的实现思路1.对于Flexbox,需要指定LayoutConfig。我们目前只需要能够识别margin和padding即可。2.measureChild中计算所有childView的宽度,然后根据childView的宽度计算当前每一行3.最后根据计算出的宽度,将所有的childView排列在中间以text为例,计算每个childView的代码如下:;childWidth=childWidth+text.getPaddingLeft()+text.getPaddingRight()+text.getMarginLeft()+text.getMarginRight();returnchildWidth;}1.初始化每一行的布局,代码如下:.MATCH_CONTENT);layoutConfig.setMargins(10,10,10,10);childLayout.setLayoutConfig(layoutConfig);returnchildLayout;}获取屏幕的宽度,代码如下:privatevoidgetParentWidthAndHeight(){Optionaldisplay=DisplayManager.getInstance().getDefaultDisplay(mContext);Pointpt=newPoint();display.get().getSize(pt);mParentWidth=(int)pt.getPointX();}动态布局:privatevoidinitChildViews(){for(inti=0;i(mParentWidth-childLayout.getMarginLeft()-childLayout.getMarginRight())){mParentLayout.addComponent(childLayout);childLayout=initDirtLayout();mLineWidth=measureChild(text);}childLayout.addComponent(text);if(i==mNames.length-1){mParentLayout.addComponent(childLayout);}}ComponentBeanbean=newComponentBean(text,false);list.add(bean);text.setClickedListener(component->{text.setSelected(!text.isSelected());mOnItemClickListener.onItemClickListener.onItemClick(text);});}}定义实现item点击事件的接口idea}Listener=onIte是不是很简单?我们只需要掌握如何计算childview的宽度,以及在什么情况下添加新行即可。更多原创请关注:https://harmonyos.51cto.com/column/30想了解更多详情请访问:https://harmonyos.51cto.com,与华为官方