如何實現抽屜式導航(ArkUI)
場景介紹
由于用戶所需功能逐漸增多,傳統的標簽式導航在個別場景已經無法滿足用戶需求。當導航欄的空間放不下過多頁簽時,可以采用抽屜式導航,本例將為大家介紹如何通過SideBarContainer組件實現抽屜式導航。
效果呈現
本例最終實現效果如下:
運行環境
- IDE:DevEco Studio 3.1 Beta1
- SDK:Ohos_sdk_public 3.2.11.9 (API Version 9 Release)
實現思路
- 通過SideBarContainer組件提供容器,通過子組件定義側邊欄和內容區,第一個子組件表示側邊欄,第二個子組件表示內容區。
- 調用showSideBar屬性來設置不顯示側邊欄,controlButton屬性來控制完成側欄的展示/收起。
開發步驟
創建內容區域文本組件。
首先創建內容區,具體代碼塊如下:
...
// 內容區
Column() {
Text("內容區域")
.width("100%")
.height("100%")
.fontSize(30)
.textAlign(TextAlign.Center)
}
.width("100%")
.height("100%")
.backgroundColor("#bbaacc")
...
通過SideBarContainer所支持的showSideBar屬性來設置不顯示側邊欄,controlButton屬性來控制完成側欄的展示/收起。
具體代碼塊如下:
...
.showSideBar(false) //默認不展示側邊欄,展示icon,用戶點擊調出
.controlButton({
left: 10, // 圖標距離左側寬度
top: 20, // 圖標距離頂部高度
height: 30, // 圖標高度
width: 30, // 圖標寬度
icons: {
shown: $r('app.media.back'), // 側邊欄展示時圖標
hidden: $r('app.media.sidebar_shown'), // 側邊欄收起時圖標
switching: $r('app.media.sidebar_shown') // 側邊欄切換過程圖標
}
})
...
創建側邊欄文本組件。
具體代碼如下:
...
struct SideBarContainerExample {
@ State navList: Array<string> = ["我的會員", "我的收藏", "我的相冊", "我的文件",]
build() {
SideBarContainer(SideBarContainerType.Embed) {
// 側邊欄內容
Column() {
ForEach(this.navList, (item) => {
Text(item)
.width("100%")
.fontSize(20)
.textAlign(TextAlign.Start)
.padding({ top: 20 })
})
}
.height("100%")
.padding({ top: 60, left: 50 })
.backgroundColor("#aabbcc")
}
...
}
}
完整代碼
示例完整代碼如下:
@Entry
@Component
struct SideBarContainerExample {
@State navList: Array<string> = ["我的會員", "我的收藏", "我的相冊", "我的文件",]
build() {
// Embed:側邊欄占據內容空間 Overlay:側邊欄懸浮于內容之上
SideBarContainer(SideBarContainerType.Embed) {
// 側邊欄內容
Column() {
ForEach(this.navList, (item) => {
Text(item)
.width("100%")
.fontSize(20)
.textAlign(TextAlign.Start)
.padding({ top: 20 })
})
}
.height("100%")
.padding({ top: 60, left: 50 })
.backgroundColor("#aabbcc")
// 內容區
Column() {
Text("內容區域")
.width("100%")
.height("100%")
.fontSize(30)
.textAlign(TextAlign.Center)
}
.width("100%")
.height("100%")
.backgroundColor("#bbaacc")
}
// 默認不展示側邊欄,展示icon,用戶點擊調出
.showSideBar(false)
.controlButton({
// 圖標距離左側寬度
left: 10,
// 圖標距離頂部高度
top: 20,
// 圖標高度
height: 30,
// 圖標寬度
width: 30,
icons: {
// 側邊欄展示時圖標
shown: $r('app.media.back'),
// 側邊欄收起時圖標
hidden: $r('app.media.sidebar_shown'),
// 側邊欄切換過程圖標
switching: $r('app.media.sidebar_shown')
}
})
// 側邊欄寬度
.sideBarWidth(200)
.width('100%')
.height('100%')
}
}
注意:模擬機與真機的預覽有區別,在SideBarContainerType.Embed情況下,真機中內容區域是壓縮,模擬器中內容區域是缺失。
總結
Tabs組件: 適用于導航欄固定在頁面上下左右側,入口分類數目不多,可以控制在5個以內,且用戶需要頻繁切換每一個頁簽的應用,比如微信、QQ等。
Navigation組件: 同樣可以實現Tabs組件中導航欄位于底部的場景,根據需要顯示隱藏導航欄,提供標題,菜單,返回等選項,使用戶是使用時更加靈活。
sideBarContainer組件:主要的功能和內容都在一個頁面里面,只是一些低頻操作內容需要顯示在其他頁面里,可以把這些輔助功能放在抽屜欄里。屏幕較小時導航欄不占用空間。比如QQ,開發指導文檔等。