介紹
瀑布流式展示圖片文字,在當(dāng)前產(chǎn)品設(shè)計(jì)中已非常常見(jiàn),本篇將介紹關(guān)于WaterFlow的圖片瀏覽場(chǎng)景,順便集成Video控件,以提高實(shí)踐的趣味性
準(zhǔn)備
- 請(qǐng)參照[官方指導(dǎo)],創(chuàng)建一個(gè)Demo工程,選擇Stage模型
- 熟讀HarmonyOS 官方指導(dǎo)“[https://gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md”]
效果
豎屏
橫屏
數(shù)據(jù)源
功能介紹
- 瀑布流式圖片展示
- 橫豎屏圖片/視頻展示
核心代碼
布局
整體結(jié)構(gòu)為:瀑布流 + 加載進(jìn)度條
每條數(shù)據(jù)結(jié)構(gòu): 圖片 + 文字 【由于沒(méi)有設(shè)定圖片寬高比,因此通過(guò)文字長(zhǎng)度來(lái)自然生成瀑布流效果】
由于有點(diǎn)數(shù)據(jù)量,按照官方指導(dǎo),采用LazyForEach懶加載方式
Stack() {
WaterFlow({ scroller: this.scroller }) {
LazyForEach(dataSource, item = > {
FlowItem() {
Column({ space: 10 }) {
Image(item.coverUrl).objectFit(ImageFit.Cover)
.width('100%')
.height(this.imageHeight)
Text(item.title)
.fontSize(px2fp(50))
.fontColor(Color.Black)
.width('100%')
}.onClick(() = > {
router.pushUrl({ url: 'custompages/waterflow/Detail', params: item })
})
}
}, item = > item)
}
.columnsTemplate(this.columnsTemplate)
.columnsGap(5)
.rowsGap(5)
.onReachStart(() = > {
console.info("onReachStart")
})
.onReachEnd(() = > {
console.info("onReachEnd")
if (!this.running) {
if ((this.pageNo + 1) * 15 < this.total) {
this.pageNo++
this.running = true
setTimeout(() = > {
this.requestData()
}, 2000)
}
}
})
.width('100%')
.height('100%')
.layoutDirection(FlexDirection.Column)
if (this.running) {
this.loadDataFooter()
}
}
復(fù)制
橫豎屏感知
橫豎屏感知整體有兩個(gè)場(chǎng)景:1. 當(dāng)前頁(yè)面發(fā)生變化 2.初次進(jìn)入頁(yè)面
這里介紹幾種監(jiān)聽(tīng)方式:
當(dāng)前頁(yè)面監(jiān)聽(tīng)
import mediaquery from '@ohos.mediaquery';
//這里你也可以使用"orientation: portrait" 參數(shù)
listener = mediaquery.matchMediaSync('(orientation: landscape)');
this.listener.on('change', 回調(diào)方法)
復(fù)制
外部傳參
通過(guò)UIAbility, 一直傳到Page文件
事件傳遞
采用EeventHub機(jī)制,在UIAbility把橫豎屏切換事件發(fā)出來(lái),Page文件注冊(cè)監(jiān)聽(tīng)事件
this.context.eventHub.on('onConfigurationUpdate', (data) = > {
console.log(JSON.stringify(data))
let config = data as Configuration
this.screenDirection = config.direction
this.configureParamsByScreenDirection()
});
復(fù)制
API數(shù)據(jù)請(qǐng)求
這里需要設(shè)置Android 或者 iOS 特征UA
requestData() {
let url = `https://api.apiopen.top/api/getHaoKanVideo?page=${this.pageNo}&size=15`
let httpRequest = http.createHttp()
httpRequest.request(
url,
{
header: {
"User-Agent": "Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36"
}
}).then((value: http.HttpResponse) = > {
if (value.responseCode == 200) {
let searchResult: SearchResult = JSON.parse(value.result as string)
if (searchResult) {
this.total = searchResult.result.total
searchResult.result.list.forEach(ItemModel = > {
dataSource.addData(ItemModel)
})
}
} else {
console.error(JSON.stringify(value))
}
}).catch(e = > {
Logger.d(JSON.stringify(e))
promptAction.showToast({
message: '網(wǎng)絡(luò)異常: ' + JSON.stringify(e),
duration: 2000
})
}).finally(() = > {
this.running = false
})
}
復(fù)制
橫豎屏布局調(diào)整
因?yàn)橐m應(yīng)橫豎屏,所以需要在原有布局的基礎(chǔ)上做一點(diǎn)改造, 讓瀑布流的列參數(shù)改造為@State 變量 , 讓圖片高度的參數(shù)改造為@State 變量
WaterFlow({ scroller: this.scroller }) {
LazyForEach(dataSource, item = > {
FlowItem() {
Column({ space: 10 }) {
Image(item.coverUrl).objectFit(ImageFit.Cover)
.width('100%')
.height(this.imageHeight)
Text(item.title)
.fontSize(px2fp(50))
.fontColor(Color.Black)
.width('100%')
}.onClick(() = > {
router.pushUrl({ url: 'custompages/waterflow/Detail', params: item })
})
}
}, item = > item)
}
.columnsTemplate(this.columnsTemplate)
復(fù)制
瀑布流完整代碼
API返回的數(shù)據(jù)結(jié)構(gòu)
import { ItemModel } from './ItemModel'
export default class SearchResult{
public code: number
public message: string
public result: childResult
}
class childResult {
public total: number
public list: ItemModel[]
};
復(fù)制
Item Model
export class ItemModel{
public id: number
public tilte: string
public userName: string
public userPic: string
public coverUrl: string
public playUrl: string
public duration: string
}復(fù)制
WaterFlow數(shù)據(jù)源接口
import List from '@ohos.util.List';
import { ItemModel } from './ItemModel';
export class PicData implements IDataSource {
private data: List< ItemModel > = new List< ItemModel >()
addData(item: ItemModel){
this.data.add(item)
}
unregisterDataChangeListener(listener: DataChangeListener): void {
}
registerDataChangeListener(listener: DataChangeListener): void {
}
getData(index: number): ItemModel {
return this.data.get(index)
}
totalCount(): number {
return this.data.length
}
}復(fù)制
布局
import http from '@ohos.net.http';
import { CommonConstants } from '../../common/CommonConstants';
import Logger from '../../common/Logger';
import { PicData } from './PicData';
import SearchResult from './Result';
import promptAction from '@ohos.promptAction'
import router from '@ohos.router';
import common from '@ohos.app.ability.common';
import { Configuration } from '@ohos.app.ability.Configuration';
import mediaquery from '@ohos.mediaquery';
let dataSource = new PicData()
/**
* 問(wèn)題: 橫豎屏切換,間距會(huì)發(fā)生偶發(fā)性變化
* 解決方案:延遲300毫秒改變參數(shù)
*
*/
@Entry
@Component
struct GridLayoutIndex {
private context = getContext(this) as common.UIAbilityContext;
@State pageNo: number = 0
total: number = 0
@State running: boolean = true
@State screenDirection: number = this.context.config.direction
@State columnsTemplate: string = '1fr 1fr'
@State imageHeight: string = '20%'
scroller: Scroller = new Scroller()
// 當(dāng)設(shè)備橫屏?xí)r條件成立
listener = mediaquery.matchMediaSync('(orientation: landscape)');
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
//橫屏
this.screenDirection = 1
} else {
//豎屏
this.screenDirection = 0
}
setTimeout(()= >{
this.configureParamsByScreenDirection()
}, 300)
}
onBackPress(){
this.context.eventHub.off('onConfigurationUpdate')
}
aboutToAppear() {
console.log('已進(jìn)入瀑布流頁(yè)面')
console.log('當(dāng)前屏幕方向:' + this.context.config.direction)
if (AppStorage.Get('screenDirection') != 'undefined') {
this.screenDirection = AppStorage.Get(CommonConstants.ScreenDirection)
}
this.configureParamsByScreenDirection()
this.eventHubFunc()
let portraitFunc = this.onPortrait.bind(this)
this.listener.on('change', portraitFunc)
this.requestData()
}
@Builder loadDataFooter() {
LoadingProgress()
.width(px2vp(150))
.height(px2vp(150))
.color(Color.Orange)
}
build() {
Stack() {
WaterFlow({ scroller: this.scroller }) {
LazyForEach(dataSource, item = > {
FlowItem() {
Column({ space: 10 }) {
Image(item.coverUrl).objectFit(ImageFit.Cover)
.width('100%')
.height(this.imageHeight)
Text(item.title)
.fontSize(px2fp(50))
.fontColor(Color.Black)
.width('100%')
}.onClick(() = > {
router.pushUrl({ url: 'custompages/waterflow/Detail', params: item })
})
}
}, item = > item)
}
.columnsTemplate(this.columnsTemplate)
.columnsGap(5)
.rowsGap(5)
.onReachStart(() = > {
console.info("onReachStart")
})
.onReachEnd(() = > {
console.info("onReachEnd")
if (!this.running) {
if ((this.pageNo + 1) * 15 < this.total) {
this.pageNo++
this.running = true
setTimeout(() = > {
this.requestData()
}, 2000)
}
}
})
.width('100%')
.height('100%')
.layoutDirection(FlexDirection.Column)
if (this.running) {
this.loadDataFooter()
}
}
}
requestData() {
let url = `https://api.apiopen.top/api/getHaoKanVideo?page=${this.pageNo}&size=15`
let httpRequest = http.createHttp()
httpRequest.request(
url,
{
header: {
"User-Agent": "Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36"
}
}).then((value: http.HttpResponse) = > {
if (value.responseCode == 200) {
let searchResult: SearchResult = JSON.parse(value.result as string)
if (searchResult) {
this.total = searchResult.result.total
searchResult.result.list.forEach(ItemModel = > {
dataSource.addData(ItemModel)
})
}
} else {
console.error(JSON.stringify(value))
}
}).catch(e = > {
Logger.d(JSON.stringify(e))
promptAction.showToast({
message: '網(wǎng)絡(luò)異常: ' + JSON.stringify(e),
duration: 2000
})
}).finally(() = > {
this.running = false
})
}
eventHubFunc() {
this.context.eventHub.on('onConfigurationUpdate', (data) = > {
console.log(JSON.stringify(data))
// let config = data as Configuration
// this.screenDirection = config.direction
// this.configureParamsByScreenDirection()
});
}
configureParamsByScreenDirection(){
if (this.screenDirection == 0) {
this.columnsTemplate = '1fr 1fr'
this.imageHeight = '20%'
} else {
this.columnsTemplate = '1fr 1fr 1fr 1fr'
this.imageHeight = '50%'
}
}
}
復(fù)制
圖片詳情頁(yè)
import { CommonConstants } from '../../common/CommonConstants';
import router from '@ohos.router';
import { ItemModel } from './ItemModel';
import common from '@ohos.app.ability.common';
import { Configuration } from '@ohos.app.ability.Configuration';
@Entry
@Component
struct DetailIndex{
private context = getContext(this) as common.UIAbilityContext;
extParams: ItemModel
@State previewUri: Resource = $r('app.media.splash')
@State curRate: PlaybackSpeed = PlaybackSpeed.Speed_Forward_1_00_X
@State isAutoPlay: boolean = false
@State showControls: boolean = true
controller: VideoController = new VideoController()
@State screenDirection: number = 0
@State videoWidth: string = '100%'
@State videoHeight: string = '70%'
@State tipWidth: string = '100%'
@State tipHeight: string = '30%'
@State componentDirection: number = FlexDirection.Column
@State tipDirection: number = FlexDirection.Column
aboutToAppear() {
console.log('準(zhǔn)備加載數(shù)據(jù)')
if(AppStorage.Get('screenDirection') != 'undefined'){
this.screenDirection = AppStorage.Get(CommonConstants.ScreenDirection)
}
this.configureParamsByScreenDirection()
this.extParams = router.getParams() as ItemModel
this.eventHubFunc()
}
onBackPress(){
this.context.eventHub.off('onConfigurationUpdate')
}
build() {
Flex({direction: this.componentDirection}){
Video({
src: this.extParams.playUrl,
previewUri: this.extParams.coverUrl,
currentProgressRate: this.curRate,
controller: this.controller,
}).width(this.videoWidth).height(this.videoHeight)
.autoPlay(this.isAutoPlay)
.objectFit(ImageFit.Contain)
.controls(this.showControls)
.onStart(() = > {
console.info('onStart')
})
.onPause(() = > {
console.info('onPause')
})
.onFinish(() = > {
console.info('onFinish')
})
.onError(() = > {
console.info('onError')
})
.onPrepared((e) = > {
console.info('onPrepared is ' + e.duration)
})
.onSeeking((e) = > {
console.info('onSeeking is ' + e.time)
})
.onSeeked((e) = > {
console.info('onSeeked is ' + e.time)
})
.onUpdate((e) = > {
console.info('onUpdate is ' + e.time)
})
Flex({direction: this.tipDirection, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center, alignContent: FlexAlign.Center}){
Row() {
Button('src').onClick(() = > {
// this.videoSrc = $rawfile('video2.mp4') // 切換視頻源
}).margin(5)
Button('previewUri').onClick(() = > {
// this.previewUri = $r('app.media.poster2') // 切換視頻預(yù)覽海報(bào)
}).margin(5)
Button('controls').onClick(() = > {
this.showControls = !this.showControls // 切換是否顯示視頻控制欄
}).margin(5)
}
Row() {
Button('start').onClick(() = > {
this.controller.start() // 開(kāi)始播放
}).margin(5)
Button('pause').onClick(() = > {
this.controller.pause() // 暫停播放
}).margin(5)
Button('stop').onClick(() = > {
this.controller.stop() // 結(jié)束播放
}).margin(5)
Button('setTime').onClick(() = > {
this.controller.setCurrentTime(10, SeekMode.Accurate) // 精準(zhǔn)跳轉(zhuǎn)到視頻的10s位置
}).margin(5)
}
Row() {
Button('rate 0.75').onClick(() = > {
this.curRate = PlaybackSpeed.Speed_Forward_0_75_X // 0.75倍速播放
}).margin(5)
Button('rate 1').onClick(() = > {
this.curRate = PlaybackSpeed.Speed_Forward_1_00_X // 原倍速播放
}).margin(5)
Button('rate 2').onClick(() = > {
this.curRate = PlaybackSpeed.Speed_Forward_2_00_X // 2倍速播放
}).margin(5)
}
}
.width(this.tipWidth).height(this.tipHeight)
}
}
eventHubFunc() {
this.context.eventHub.on('onConfigurationUpdate', (data) = > {
console.log(JSON.stringify(data))
let config = data as Configuration
this.screenDirection = config.direction
this.configureParamsByScreenDirection()
});
}
configureParamsByScreenDirection(){
if(this.screenDirection == 0){
this.videoWidth = '100%'
this.videoHeight = '70%'
this.tipWidth = '100%'
this.tipHeight = '30%'
this.componentDirection = FlexDirection.Column
} else {
this.videoWidth = '60%'
this.videoHeight = '100%'
this.tipWidth = '40%'
this.tipHeight = '100%'
this.componentDirection = FlexDirection.Row
}
}
}
審核編輯 黃宇
-
鴻蒙
+關(guān)注
關(guān)注
57文章
2352瀏覽量
42859 -
HarmonyOS
+關(guān)注
關(guān)注
79文章
1975瀏覽量
30201 -
鴻蒙OS
+關(guān)注
關(guān)注
0文章
188瀏覽量
4396
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論