【HarmonyOS】自定義組件之ArkUI實現通用標題欄組件

 【關鍵字】

標題欄、常用內置組件整合、ArkUI、自定義組件

 

1、寫在前面

在上一篇文章中我們通過Java語言實現了一個通用的標題欄組件,有需要的可以看下,文章地址:

https://developer.huawei.com/consumer/cn/forum/topic/0202117373459738584?fid=0101587866109860105

現在很多朋友都已經轉戰ArkTS語言了,那麼今天就來使用ArkTS實現一個同樣的通用標題欄組件,樣式選擇還和之前保持一致,左側文本按鈕、中間文本、右側圖片按鈕,關於樣式,大家可以自行根據項目實際需求進行修改,廢話不多說,下面進入代碼實戰吧!

2、自定義標題欄

首先,新建一個CommonTitleBar.ets文件,在該文件中封裝通用標題欄組件:

cke_501.png

然後,定義標題欄組件需要的相關屬性:

cke_1153.png

最後,在標題欄組件類中使用內置組件拼裝組合,創建上面定義的屬性類的類型的變量,在內置組件中的相應屬性通過該變量控制,如下圖所示:

cke_1999.png

完整的自定義標題欄組件代碼如下:

@Component
export struct CommonTitleBar {
  // 標題欄屬性
  public attribute: CommonTitleBarAttribute;

  build() {
    Flex() {
      Stack({ alignContent: Alignment.Start }) {
        Text(this.attribute.close_text)
          .fontSize(16)
          .width(60)
          .height('100%')
          .onClick(() => {
            this.attribute.closeCallback?.call(this)
          })
      }
      .padding({ left: 15 })
      .layoutWeight(1)

      Stack({ alignContent: Alignment.Center }) {
        Text(this.attribute.title_text)
          .fontSize(16)
          .fontColor('#0000ff')
          .width(60)
          .textAlign(TextAlign.Center)
          .height('100%')
      }
      .layoutWeight(2)

      Stack({ alignContent: Alignment.End }) {
        Image($r('app.media.menu'))
          .width(40)
          .height(40)
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            this.attribute.menuCallback?.call(this)
          })
      }
      .padding({ right: 15 })
      .height('100%')
      .layoutWeight(1)
    }
    .width('100%')
    .height(48)
    .backgroundColor(this.attribute.bg_color)
  }
}

// 定義標題欄屬性
class CommonTitleBarAttribute {
  public bg_color: string = ""; // 標題欄背景色

  public close_text: string = ""; // 關閉按鈕文字
  public closeCallback: () => void; // 關閉按鈕事件回調

  public title_text: string = ""; // 標題文字

  public menuCallback: () => void; // 菜單按鈕事件回調
}

3、使用標題欄組件

上面定義好了標題欄組件,下面開始在別的頁面引用該組件,在首頁Index.ets中引用,首先導入該組件:

cke_5402.png

然後引用該組件,爲組件配置相應的屬性值:

cke_7898.png

完整代碼如下:

import prompt from '@ohos.prompt';
import { CommonTitleBar } from './CommonTitleBar';

@Entry
@Component
struct Index {
  build() {
    Column() {
      CommonTitleBar({attribute:{
        bg_color:'#ff2ad4b2',
        close_text: '返回',
        closeCallback:()=>{
          prompt.showToast({
            message: '點擊返回按鈕',
            duration: 2000
          });
        },
        title_text: '標題',
        menuCallback:()=>{
          prompt.showToast({
            message: '點擊菜單按鈕',
            duration: 2000
          });
        }
      }})
      Text('內容')
        .fontSize(20)
        .textAlign(TextAlign.Center)
        .width('100%')
        .height('100%')
    }
    .width('100%')
    .height('100%')
  }
}

最後一起來看一下實現的效果吧:

cke_12936.pngcke_14700.png

 

 

 

 欲瞭解更多更全技術文章,歡迎訪問https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章