HarmonyOS 鸿蒙Next 如何实现和父布局保持一定间距并充满剩余部分的样式?

HarmonyOS 鸿蒙Next 如何实现和父布局保持一定间距并充满剩余部分的样式?

问题背景

在学习鸿蒙开发的过程中,尝试构建一个以前开发过的页面,其中有个元素是Edittext输入区域,背景为一条线,大约是这样的感觉

![]

在开发Android的时候,我是通过把背景设置为一个drawable,然后在xml文件中画一条线实现的,现在尝试学习鸿蒙,使用TextInput,在文档中没有找到设置背景为一个自定义布局的API,于是尝试在TextInput下方画一条线来实现,代码如下:

Column() {
  TextInput({ placeholder: $r("app.string.pleaseInputPhoneNum") })
    .backgroundColor($r("app.color.color_FFFFFF"))
    .margin({ left: 24, top: 48 })
    .padding(0)
  Line().width("100%").height(1)
    .backgroundColor($r("app.color.color_1A1D1B"))
    .margin(15)
}.width("100%")
.height("100%")
.alignItems(HorizontalAlign.Start)

然后,这条线按照设计应该是距离父布局(此处为屏幕边缘)一段固定距离,然后充满剩下的部分,按照Android的写法应该是把宽度设置为match_parent,然后左右margin即可,但是在这边出现了问题,写宽度为100%真就是和父布局等宽,设置左右margin,线条直接就超出屏幕范围了。

问题

  1. 如何才能让一个UI组件在和父布局保持一定间距的同时充满剩余空间?暂时不考虑使用flex布局,因为会有额外的开销,出处1 出处2

  2. 如果不在TextInput下划线,还有什么方式能实现这种UI效果?最好是能用背景实现的,因为说不定会有设计师想要在获取焦点的时候变化线条颜色


更多关于HarmonyOS 鸿蒙Next 如何实现和父布局保持一定间距并充满剩余部分的样式?的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复
Column() {
  Line().width("100%").height(1)
    .backgroundColor($r("app.color.color_1A1D1B"))
    .margin(15)
}.width("100%").padding({ left: 10, right: 10 })

套多一层,改变颜色直接将 backgroundColor 的属性设置为 @State 就行

更多关于HarmonyOS 鸿蒙Next 如何实现和父布局保持一定间距并充满剩余部分的样式?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


懂了,多一层父布局,使用父布局的padding来限制子布局的宽度,但是在这种情况下,子布局的margin会有可能失效是什么情况?

比如就使用你列出的代码,子布局Line的宽度100%,左右margin设置为相同数值的时候就会互相抵消,设置不同数值的时候就会导致位置偏移直至把一边推到屏幕之外?而且这个抵消还不是线性的,比如left为20,right要设置到39才能刚好让左边贴边。

感觉这个问题和UI的绘制逻辑有关,并不像是Android那样先确定好父布局的大小,然后在父布局的padding之内绘制子布局。

可以了解一下盒模型,margin 和 padding 的差异,这里的抵消应该是和元素中心位置相关,具体的可以不用关心,你如果要用 margin 就放父元素,如果要 line 左右偏移就重新调整父元素的 padding 就好。

在HarmonyOS鸿蒙Next中,要实现和父布局保持一定间距并充满剩余部分的样式,可以使用DirectionalLayoutDependentLayout进行布局管理。

  1. 使用DirectionalLayout

    • 设置DirectionalLayout为垂直或水平布局。
    • 在子组件中使用layout_weight属性,使其根据权重分配剩余空间。
    • 使用margin属性设置与父布局的间距。

    示例代码:

    <DirectionalLayout
        ohos:width="match_parent"
        ohos:height="match_parent"
        ohos:orientation="vertical">
        <Component
            ohos:width="match_parent"
            ohos:height="0dp"
            ohos:margin="20vp"
            ohos:layout_weight="1"/>
    </DirectionalLayout>
    
  2. 使用DependentLayout

    • 使用DependentLayout结合alignmentmargin属性,实现与父布局的间距。
    • 使用layout_widthlayout_height设置为match_parent,使子组件充满剩余空间。

    示例代码:

    <DependentLayout
        ohos:width="match_parent"
        ohos:height="match_parent">
        <Component
            ohos:width="match_parent"
            ohos:height="match_parent"
            ohos:alignment="center"
            ohos:margin="20vp"/>
    </DependentLayout>
    

通过以上方法,可以实现与父布局保持一定间距并充满剩余部分的样式。

回到顶部