《探索 HarmonyOS NEXT(5.0):开启构建模块化项目架构奇幻之旅 —— Tabs底部导航栏》

简介

通过学习HarmonyOS Next,实战项目WanAndroid 鸿蒙版,API接口均来自WanAndroid 开源接口,我们一起来做个App吧。

玩Android 开放APIhttps://www.wanandroid.com/blog/show/2

效果图

创建每个模块下的各个目录

1、features基础特性层下面的模块对应的目录


    features                                       # 基础特性层,包含独立的业务模块,如启动页、登录模块等              
    |---home                                       // 首页
    |   |---bean                                   // 数据模型
    |   |---components                             // 自定义组件
    |   |---constants                              // 常量
    |   |---model                                  // 业务模型
    |   |---service                                // 业务服务/接口
    |   |---views                                  // 视图层
    |   |---utils                                  // 此模块工具类 需要再加    
    |---login                                      // 登录
    |---question                                   // 问答
    |---scheme                                     // 体系
    |---mine                                       // 我的
    |---login                                      // 登录 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2、products产品定制层下面的模块对应的目录

    products                                       # 产品定制层,作为不同设备或场景应用入口,例如phone、tv等
    |---phone                                      // 手机
    |   |---app                                    // 全局初始化配置
    |   |---bean                                   // 数据模型
    |   |---components                             // 自定义组件 
    |   |---constants                              // 常量
    |   |---model                                  // 业务模型
    |   |---pages                                  // 页面 
    |   |---service                                // 业务服务/接口
    |   |---test                                   // 测试某个效果的例子
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

创建后就可以搭建了。

使用Tabs搭建底部导航栏

  • 详细使用步骤还得去官方(选项卡 (Tabs))去学习,再来看就一目了然了.

1、通过上面图一底部导航栏分为上面图片,下面是文字,选中都变颜色,定义一个对象的结构,命名为TabModel,因为后期可能为公共的,所以位置放在uicomponents模块model目录。

    export interface TabModel {
      index: number; // 下标
      title: string; // 标题
      selectImage: Resource; // 选中图片
      // unSelectImage: Resource; // 未选中图片
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2、组装数据,定义一个首页底部Tab数据,图片资源都在源码里。


/**
 * 首页底部Tab显示数据
 */
 
export const tabBarModel: Array<TabModel> = [
  {
    index: 0,
    title: '首页',
    selectImage: $r('app.media.ic_bottom_bar_home'),
  },
  {
    index: 1,
    title: '问答',
    selectImage: $r('app.media.ic_bottom_bar_ques'),
  },
  {
    index: 2,
    title: '体系',
    selectImage: $r("app.media.ic_bottom_bar_scheme"),
  },
  {
    index: 3,
    title: '我的',
    selectImage: $r('app.media.ic_bottom_bar_mine'),
  }

]
  • 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

3、搭建Tabs

  • 定义一个选中的index
  • 设置为底部导航时,需要将barPosition设置为BarPosition.End。
  • 鼠标放到Tabs上,可以查看对应的API,很方便

  • 自定义导航栏,通过TabContent的tabBar

    Column() {
      Divider().color($r('app.color.color_F0F0F0'))
      Badge({
        count: index != 1 ? 0 : this.msgCount,
        position: BadgePosition.RightTop,
        style: {
          fontSize: 8,
          badgeSize: 13
        }
      }) {
        Image(item.selectImage /*this.selectedIndex == index ? item.selectImage : item.unSelectImage*/)
          .colorBlend(this.selectedIndex == index ? $r('app.color.colorPrimary') : $r('app.color.color_222222'))
          .height(24)
          .margin(4)
      }.margin({ top: 4 })

      Text(item.title)
        .width(CommonConst.FULL_PARENT)
        .fontSize(14)
        .fontWeight(500)
        .textAlign(TextAlign.Center)
        .fontColor(this.selectedIndex == index ? $r('app.color.colorPrimary') : $r('app.color.color_222222'))
        .margin({ bottom: 4 })
    }
    .width(CommonConst.FULL_PARENT)
    .height(CommonConst.FULL_PARENT)
    .backgroundColor($r('app.color.white'))
  • 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
  • !!!选中的图片如果只是变了颜色,其实不用再单独设置一个选中的图片,可以通过Image的colorBlend来设置选中图片

4、效果为

  • 把中间内容区域换成每个模块对应的页面,分别是

@Builder
tabContentBuilder(item: TabModel) {
  if (item.index == 0) {
    // 首页
    HomeView()
  } else if (item.index == 1) {
    // 问答
    QuestionView()
  } else if (item.index == 2) {
    // 体系
    SchemeView()
  } else if (item.index == 3) {
    // 我的
    MineView()
  }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

切换导致的问题

  • 每次切换都重新加载,这肯定对用户的体验是不好的,那我们通过存储每个页面的状态来实现,就初始化一次。

  • 定义一个数组,存储状态
    //存储页面状态
    @Local tabContentArr: boolean[] = [true, false, false, false]
  • 1
  • 2
  • 切换的时候状态设置为true
    .onChange((index: number) => {
      this.selectedIndex = index;
      this.tabContentArr[index] = true;
    })
  • 1
  • 2
  • 3
  • 4
  • 加载视图判断

    if (this.selectedIndex === index || this.tabContentArr[index]) {
      this.tabContentBuilder(item)
    }
  • 1
  • 2
  • 3
  • 4
  • 最终效果为

完整代码

    @Preview
    @ComponentV2
    export struct MainPage {
      @Local selectedIndex: number = 0 // 当前选中的tab下标
      @Local msgCount: number = 9 // 消息数量
      //存储页面状态
      @Local tabContentArr: boolean[] = [true, false, false, false]

      build() {
        Stack() {
          Tabs({ index: this.selectedIndex, barPosition: BarPosition.End }) {
            ForEach(tabBarModel, (item: TabModel, index: number) => {
              TabContent() {
                if (this.selectedIndex === index || this.tabContentArr[index]) {
                  this.tabContentBuilder(item)
                }
              }.tabBar(this.tabBottom(tabBarModel[item.index], item.index))
            }, (item: string) => item)

          }.barWidth(CommonConst.FULL_PARENT)
          .barHeight(56) //设置导航栏高度
          .scrollable(false) // 禁止左右滑动
          .onChange((index: number) => {
            this.selectedIndex = index;
            this.tabContentArr[index] = true;
          })
        }.width(CommonConst.FULL_PARENT)
        .height(CommonConst.FULL_PARENT)

      }

      @Builder
      tabContentBuilder(item: TabModel) {
        if (item.index == 0) {
          // 首页
          HomeView()
        } else if (item.index == 1) {
          // 问答
          QuestionView()
        } else if (item.index == 2) {
          // 体系
          SchemeView()
        } else if (item.index == 3) {
          // 我的
          MineView()
        }

      }

      @Builder
      tabBottom(item: TabModel, index: number) {
        Column() {
          Divider().color($r('app.color.color_F0F0F0'))
          Badge({
            count: index != 1 ? 0 : this.msgCount,
            position: BadgePosition.RightTop,
            style: {
              fontSize: 8,
              badgeSize: 13
            }
          }) {
            Image(item.selectImage /*this.selectedIndex == index ? item.selectImage : item.unSelectImage*/)
              .colorBlend(this.selectedIndex == index ? $r('app.color.colorPrimary') : $r('app.color.color_222222'))
              .height(24)
              .margin(4)
          }.margin({ top: 4 })

          Text(item.title)
            .width(CommonConst.FULL_PARENT)
            .fontSize(14)
            .fontWeight(500)
            .textAlign(TextAlign.Center)
            .fontColor(this.selectedIndex == index ? $r('app.color.colorPrimary') : $r('app.color.color_222222'))
            .margin({ bottom: 4 })
        }
        .width(CommonConst.FULL_PARENT)
        .height(CommonConst.FULL_PARENT)
        .backgroundColor($r('app.color.white'))

      }
    }
  • 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
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81

短时间内连续点击两次才能退出应用

  • 定义一个状态变量来记录上次点击返回键的时间
let lastBackPressedTime = 0
  • 1
  • 在onBackPressed里处理
 .onBackPressed(() => {
      const currentTime = new Date().getTime()
      const timeDifference = currentTime - lastBackPressedTime
      if (timeDifference < 2000) { // 2秒内再次点击
        //退出应用
        AppUtil.exit()  // 此方法来自于大佬的 harmony-utils
      } else {
        // 提示用户
        ToastUtil.showToast('再按一次退出应用')
        lastBackPressedTime = currentTime
      }

      return true
    })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

工程目录,请看README.md

https://gitee.com/jiaojiaoone/explore-harmony-next/blob/master/README.md

  • 以往系列文章
  1. 《探索 HarmonyOS NEXT(5.0):开启构建模块化项目架构奇幻之旅 —— 模块化基础篇》
  2. 《探索 HarmonyOS NEXT(5.0):开启构建模块化项目架构奇幻之旅 —— 构建基础特性层》
  3. 《探索 HarmonyOS NEXT(5.0):开启构建模块化项目架构奇幻之旅 —— 构建公共能力层》

若本文对您稍有帮助,诚望您不吝点赞,多谢。

有兴趣的同学可以点击查看源码

欢迎加我微信一起交流:+V:yinshiyuba

本文使用 文章同步助手 同步

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容