【组件】自定义页面顶部标题栏组件,可动态设置标题、左右操作按钮icon及点击事件

与辉鸿蒙
发布于 2024-11-9 18:41
浏览
1收藏

使用自己封装的标题栏容器组件,可以满足页面常用的顶部标题栏功能及样式的需求。
常见的标题栏

  1. 返回按钮+标题
    【组件】自定义页面顶部标题栏组件,可动态设置标题、左右操作按钮icon及点击事件-鸿蒙开发者社区
  2. 返回按钮+标题+功能按钮
    【组件】自定义页面顶部标题栏组件,可动态设置标题、左右操作按钮icon及点击事件-鸿蒙开发者社区
  3. 关闭/取消按钮+标题+确认/完成按钮
    【组件】自定义页面顶部标题栏组件,可动态设置标题、左右操作按钮icon及点击事件-鸿蒙开发者社区
    组件TitleContainer.ets代码如下:
@Preview
@Component
export default struct TitleContainer {
  // 返回按钮图片
  private backImg: string | Resource = $r("app.media.icon_cancel");
  // 返回按钮点击事件
  private backFunc?: () => void;
  // 标题
  private title: string | Resource = "标题";
  // 关闭按钮点击事件
  @BuilderParam closeHandle?: () => void;

  build() {
    Row() {
      // 返回按钮
      Button() {
        Image(this.backImg == null ? $r("app.media.icon_back") : this.backImg)
          .objectFit(ImageFit.Fill);
      }
      .width(24)
      .height(24)
      .backgroundColor("#00000000")
      .onClick(() => {
        this.backFunc ? this.backFunc : router.back();
      });

      // 标题
      Text(this.title)
        .fontSize(20)
        .lineHeight(28)
        .fontColor("#182431")
        .fontWeight(FontWeight.Bold)
        .margin({ left: 16 });

      // 占位
      Blank()

      if (this.closeHandle) {
        this.closeHandle();
      }
    }
    .width("100%")
    .height(56)
    .padding({
      left: 24,
      right: 24
    })
  }
}


  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.

使用组件的页面Home.ets代码如下:


@Entry
@Component
struct Home {
  @State message: string = '主页面'
  build() {
    Row() {
      Column() {
        TitleContainer({
          title: "Hello World",
          closeHandle: () => {
          } })
          .backgroundColor(Color.White)
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .fontColor(Color.White)
          .margin({ top: 50 })
      }
      .width('100%')
    }
    .height('100%')
    .alignItems(VerticalAlign.Top)
    .backgroundColor(Color.Gray)
  }
}


  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.

预览效果如下:
组件预览
【组件】自定义页面顶部标题栏组件,可动态设置标题、左右操作按钮icon及点击事件-鸿蒙开发者社区
使用组件的页面预览
【组件】自定义页面顶部标题栏组件,可动态设置标题、左右操作按钮icon及点击事件-鸿蒙开发者社区

1
收藏 1
回复
举报
1
1
回复
    相关推荐