鴻蒙音樂應用開發:從收藏功能實現看狀態管理與交互設計
在移動應用開發中,收藏功能是用戶體驗的重要組成部分。本文將以鴻蒙OS音樂應用為例,詳細解析如何實現具有動畫效果的收藏功能,涉及狀態管理、組件通信和交互動畫等核心技術點。
一、收藏功能的核心數據模型設計
首先定義Song
數據模型,通過@Observed
裝飾器實現數據響應式:
@Observed
class Song {id: string = ''title: string = ''singer: string = ''mark: string = "1" // 音樂品質標識,1:sq, 2:viplabel: Resource = $r('app.media.ic_music_icon') // 歌曲封面src: string = '' // 播放路徑lyric: string = '' // 歌詞路徑isCollected: boolean = false // 收藏狀態constructor(id: string, title: string, singer: string, mark: string, label: Resource, src: string, lyric: string, isCollected: boolean) {this.id = idthis.title = titlethis.singer = singerthis.mark = markthis.label = labelthis.src = srcthis.lyric = lyricthis.isCollected = isCollected}
}
isCollected
字段作為收藏狀態的核心標識,配合@Observed
實現數據變更時的UI自動更新。
二、首頁與收藏頁的整體架構
應用采用標簽頁架構,通過Tabs
組件實現"首頁"與"我的"頁面切換:
@Entry
@Component
struct Index {@State currentIndex: number = 0@State songList: Array<Song> = [// 歌曲列表初始化new Song('1', '海闊天空', 'Beyond', '1', $r('app.media.ic_music_icon'), 'common/music/1.mp3', 'common/music/1.lrc', false),// 省略其他歌曲...]@BuildertabStyle(index: number, title: string, selectedImg: Resource, unselectedImg: Resource) {Column() {Image(this.currentIndex == index ? selectedImg : unselectedImg).width(20).height(20)Text(title).fontSize(16).fontColor(this.currentIndex == index ? "#ff1456" : '#ff3e4040')}}build() {Tabs() {TabContent() {RecommendedMusic({ songList: this.songList })}.tabBar(this.tabStyle(0, '首頁', $r('app.media.home_selected'), $r("app.media.home")))TabContent() {CollectedMusic({ songList: this.songList })}.tabBar(this.tabStyle(1, '我的', $r('app.media.userfilling_selected'), $r("app.media.userfilling")))}.barPosition(BarPosition.End).width("100%").height("100%")}
}
通過@State
管理標簽頁索引currentIndex
,當用戶切換標簽時,自動更新UI顯示推薦歌曲或收藏歌曲。
三、收藏功能的核心實現:狀態切換與動畫效果
在歌曲列表項組件中,實現收藏狀態切換邏輯與動畫效果:
@Component
export struct SongListItem {@Prop song: Song@Link songList: Array<Song>@Prop index: number// 動畫狀態標識@State isAnimating: boolean = false/*** 收藏狀態切換方法*/collectStatusChange(): void {// 1. 切換當前歌曲收藏狀態this.song.isCollected = !this.song.isCollected// 2. 更新列表中對應歌曲的狀態this.songList = this.songList.map(item => {if (item.id === this.song.id) {item.isCollected = this.song.isCollected}return item})// 3. 觸發收藏動畫this.isAnimating = truesetTimeout(() => {this.isAnimating = false}, 300)// 4. 發送收藏事件(可用于全局狀態同步)getContext(this).eventHub.emit('collected', this.song.id, this.song.isCollected ? '1' : '0')}build() {Column() {Row() {Column() {Text(this.song.title).fontWeight(500).fontSize(16).margin({ bottom: 4 })Row({ space: 4 }) {Image(this.song.mark === '1' ? $r('app.media.ic_vip') : $r('app.media.ic_sq')).width(16).height(16)Text(this.song.singer).fontSize(12)}}.alignItems(HorizontalAlign.Start)// 收藏圖標帶動畫效果Image(this.song.isCollected ? $r('app.media.ic_item_collected') : $r('app.media.ic_item_uncollected')).width(50).height(50).padding(13).scale({ x: this.isAnimating ? 1.8 : 1, y: this.isAnimating ? 1.8 : 1 }).animation({ duration: 300, curve: Curve.EaseOut }).onClick(() => this.collectStatusChange())}.width("100%").padding({ left: 16, right: 16, top: 12, bottom: 12 })}.width("100%")}
}
核心動畫效果通過scale
變換和animation
配置實現:
- 點擊時圖標放大至1.8倍
- 300ms的緩出動畫(
Curve.EaseOut
) isAnimating
狀態控制動畫的觸發與結束
四、收藏列表的篩選與展示
"我的"頁面通過filter
方法篩選已收藏歌曲:
@Component
export struct CollectedMusic {@Link songList: Array<Song>build() {Column(){Text('收藏').fontSize(26).fontWeight(700).height(56).width('100%').padding({ left: 16, right: 16 })List(){ForEach(this.songList.filter(song => song.isCollected), (song: Song, index: number) => {ListItem() {SongListItem({ song: song, songList: this.songList })}}, (song: Song) => song.id)}.cachedCount(3).divider({ strokeWidth: 1, color: "#E5E5E5" }).scrollBar(BarState.Off)}.width("100%").height("100%")}
}
通過filter(song => song.isCollected)
實現已收藏歌曲的精準篩選,確保"我的"頁面只顯示用戶收藏的內容。
五、附:代碼
import { promptAction } from "@kit.ArkUI"@Observed
class Song {id: string = ''title: string = ''singer: string = ''// 音樂品質標識,1:sq,2:vipmark: string = "1"// 歌曲封面圖片label: Resource = $r('app.media.ic_music_icon')// 歌曲播放路徑src: string = ''// 歌詞文件路徑lyric: string = ''// 收藏狀態, true:已收藏 false:未收藏isCollected: boolean = falseconstructor(id: string, title: string, singer: string, mark: string, label: Resource, src: string, lyric: string, isCollected: boolean) {this.id = idthis.title = titlethis.singer = singerthis.mark = markthis.label = labelthis.src = srcthis.lyric = lyricthis.isCollected = isCollected}
}@Entry
@Component
struct Index {@State currentIndex: number = 0// 存儲收藏歌曲列表@State songList: Array<Song> = [new Song('1', '海闊天空', 'Beyond', '1', $r('app.media.ic_music_icon'), 'common/music/1.mp3', 'common/music/1.lrc', false),new Song('2', '夜空中最亮的星', '逃跑計劃', '1', $r('app.media.ic_music_icon'), 'common/music/2.mp3', 'common/music/2.lrc', false),new Song('3', '光年之外', 'GAI周延', '2', $r('app.media.ic_music_icon'), 'common/music/3.mp3', 'common/music/3.lrc', false),new Song('4', '起風了', '買辣椒也用券', '1', $r('app.media.ic_music_icon'), 'common/music/4.mp3', 'common/music/4.lrc', false),new Song('5', '孤勇者', '陳奕迅', '2', $r('app.media.ic_music_icon'), 'common/music/5.mp3', 'common/music/5.lrc', false)]@BuildertabStyle(index: number, title: string, selectedImg: Resource, unselectedImg: Resource) {Column() {Image(this.currentIndex == index ? selectedImg : unselectedImg).width(20).height(20)Text(title).fontSize(16).fontColor(this.currentIndex == index ? "#ff1456" : '#ff3e4040')}}build() {Tabs() {TabContent() {// 首頁標簽內容RecommendedMusic({ songList: this.songList})}.tabBar(this.tabStyle(0, '首頁', $r('app.media.home_selected'), $r("app.media.home")))TabContent() {// 我的標簽內容占位CollectedMusic({ songList: this.songList})}.tabBar(this.tabStyle(1, '我的', $r('app.media.userfilling_selected'), $r("app.media.userfilling")))}.barPosition(BarPosition.End).width("100%").height("100%").onChange((index: number) => {this.currentIndex = index})}
}// 推薦歌單
@Component
export struct RecommendedMusic {// 創建路由棧管理導航@Provide('navPath') pathStack: NavPathStack = new NavPathStack()// 熱門歌單標題列表@State playListsTiles: string[] = ['每日推薦', '熱門排行榜', '經典老歌', '流行金曲', '輕音樂精選']@Link songList: Array<Song>@BuildershopPage(name: string, params:string[]) {if (name === 'HotPlaylist') {HotPlayList({songList: this.songList});}}build() {Navigation(this.pathStack) {Scroll() {Column() {// 推薦標題欄Text('推薦').fontSize(26).fontWeight(700).height(56).width('100%').padding({ left: 16, right: 16 })// 水平滾動歌單列表List({ space: 10 }) {ForEach(this.playListsTiles, (item: string, index: number) => {ListItem() {HotListPlayItem({ title: item }).margin({left: index === 0 ? 16 : 0,right: index === this.playListsTiles.length - 1 ? 16 : 0}).onClick(() => {this.pathStack.pushPathByName('HotPlaylist', [item])})}}, (item: string) => item)}.height(200).width("100%").listDirection(Axis.Horizontal).edgeEffect(EdgeEffect.None).scrollBar(BarState.Off)// 熱門歌曲標題欄Text('熱門歌曲').fontSize(22).fontWeight(700).height(56).width('100%').padding({ left: 16, right: 16 })// 歌曲列表List() {ForEach(this.songList, (song: Song, index: number) => {ListItem() {SongListItem({ song: song, index: index,songList: this.songList})}}, (song: Song) => song.id)}.cachedCount(3).divider({strokeWidth: 1,color: "#E5E5E5",startMargin: 16,endMargin: 16}).scrollBar(BarState.Off).nestedScroll({scrollForward: NestedScrollMode.PARENT_FIRST,scrollBackward: NestedScrollMode.SELF_FIRST})}.width("100%")}.scrollBar(BarState.Off)}.hideTitleBar(true).mode(NavigationMode.Stack).navDestination(this.shopPage)}
}
// 熱門歌單
@Component
export struct HotListPlayItem {@Prop title: string // 接收外部傳入的標題build() {Stack() {// 背景圖片Image($r('app.media.cover5')).width("100%").height('100%').objectFit(ImageFit.Cover).borderRadius(16)// 底部信息欄Row() {Column() {// 歌單標題Text(this.title).fontSize(20).fontWeight(700).fontColor("#ffffff")// 輔助文本Text("這個歌單很好聽").fontSize(16).fontColor("#efefef").height(12).margin({ top: 5 })}.justifyContent(FlexAlign.SpaceBetween).alignItems(HorizontalAlign.Start).layoutWeight(1)// 播放按鈕SymbolGlyph($r('sys.symbol.play_round_triangle_fill')).fontSize(36).fontColor(['#99ffffff'])}.backgroundColor("#26000000").padding({ left: 12, right: 12 }).height(72).width("100%")}.clip(true).width(220).height(200).align(Alignment.Bottom).borderRadius({ bottomLeft: 16, bottomRight: 16 })}
}// 歌曲列表項
@Component
export struct SongListItem {//定義當前歌曲,此歌曲是由前面通過遍歷出來的單個數據@Prop song: Song@Link songList: Array<Song>//當前點擊歌曲的index值@Prop index: number/*** 點擊紅心收藏效果*/collectStatusChange(): void {const songs = this.song// 切換收藏狀態this.song.isCollected = !this.song.isCollected// 更新收藏列表this.songList = this.songList.map((item) => {if (item.id === songs.id) {item.isCollected = songs.isCollected}return item})promptAction.showToast({message: this.song.isCollected ? '收藏成功' : '已取消收藏',duration: 1500});// 觸發全局收藏事件getContext(this).eventHub.emit('collected', this.song.id, this.song.isCollected ? '1' : '0')}aboutToAppear(): void {// 初始化歌曲數據(如果需要)}build() {Column() {Row() {Column() {Text(this.song.title).fontWeight(500).fontColor('#ff070707').fontSize(16).margin({ bottom: 4 })Row({ space: 4 }) {Image(this.song.mark === '1' ? $r('app.media.ic_vip') : $r('app.media.ic_sq')).width(16).height(16)Text(this.song.singer).fontSize(12).fontWeight(400).fontColor('#ff070707')}}.alignItems(HorizontalAlign.Start)Image(this.song.isCollected ? $r('app.media.ic_item_collected') : $r('app.media.ic_item_uncollected')).width(50).height(50).padding(13).onClick(() => {this.collectStatusChange()})}.width("100%").justifyContent(FlexAlign.SpaceBetween).padding({left: 16,right: 16,top: 12,bottom: 12}).onClick(() => {// 設置當前播放歌曲this.song = this.song// todo: 添加播放邏輯})}.width("100%")}
}@Component
export struct HotPlayList {@Prop title:string@Link songList: Array<Song>build() {NavDestination(){List(){ForEach(this.songList,(song:Song)=>{ListItem(){SongListItem({song:song,songList:this.songList})}},(song:Song)=>song.id)}.cachedCount(3).divider({strokeWidth:1,color:"#E5E5E5",startMargin:16,endMargin:16}).scrollBar(BarState.Off)}.width("100%").height("100%").title(this.title)}
}@Component
export struct CollectedMusic {@Link songList: Array<Song>build() {Column(){Text('收藏').fontSize(26).fontWeight(700).height(56).width('100%').padding({ left: 16, right: 16 })List(){ForEach(this.songList.filter((song) => song.isCollected),(song:Song,index:number)=>{ListItem(){SongListItem({song:song,songList:this.songList})}},(song:Song)=>song.id)}.cachedCount(3).layoutWeight(1).divider({strokeWidth:1,color:"#E5E5E5",startMargin:16,endMargin:16}).scrollBar(BarState.Off)}.width("100%").height("100%")}
}