一、 效果展示
二、 功能概述
发现页面通过Tabs和TabContent组件实现选项卡“推荐”与“关注”的切换。每个选项都有对应的图标和标题,图片的样式会根据当前选中的页面角标而变化。
我的页面展示本页面的用户的头像,提供用户资料,收藏,服务,设置选项展示。
三、 组件实现
1 . 通过TabBarBuilder方法定义底部图标样式,并在TabContent中使用.tabBar方法应用样式。
2. 发现页面包括头部搜索栏组件SearchHeader和热点组件。
2. 热点组件中使用List容器,使新闻可以上下滑动。
3. 使用Column容器包含我的页面的内容,用row容器展示,和分割线组件divder实现分隔。
四、 完整代码展示
1. 发现页面Discovery.ets
/**
* 发现组件
*/
import SearchHeader from '../record/SearchHeader'
import HotSpotCard from './HotSpotCard'
@Component
export default struct Discovery{
build() {
Column(){
// 1. 头部搜索栏
SearchHeader()
// 2. 热点
HotSpotCard()
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.index_page_background'))
}
}
2. SearchHeader.ets
/**
* 头部搜索栏组件
*/
import { CommonConstants } from '../../common/constants/CommonConstants'
@Component
export default struct SearchHeader {
build() {
Row({space: CommonConstants.SPACE_6}){
/**
* 搜索栏组件Search和TextInput使用相似
*/
Search({placeholder: '搜索饮食或运动信息'})//搜索提示
.textFont({size: 18})//字体信息
.layoutWeight(1)//占据剩余空间
/**
* 组件Bage 角标/小数字显示
*/
Badge({count: 1, position: BadgePosition.RightTop, style: {fontSize: 12}}){
Image($r('app.media.ic_public_email'))
.width(24)
}
}
.width(CommonConstants.THOUSANDTH_940)
}
}
3. 热点组件HotSpotCard.ets
/**
* 热点组件
*/
@Component
export default struct HotSpotCard{
private arr=[
{img:$r('app.media.weibo1')},
{img:$r('app.media.weibo3')},
{img:$r('app.media.weibo4')},
{img:$r('app.media.weibo2')}
]
build() {
// 1. 标题
Tabs() {
TabContent() {
Column() {
List({ space: 10}) {
ForEach(this.arr, (item) => {
ListItem() {
Image(item.img)
.width('100%')
}
})
}
.listDirection(Axis.Vertical) // 排列方向
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // 每行之间的分界线
.edgeEffect(EdgeEffect.Spring) // 滑动到边缘无效果
.onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex)
console.info('last' + lastIndex)
})
.width('90%')
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 })
}
.tabBar('推荐')
TabContent() {
Image($r('app.media.weibo2'))
.width('100%')
.margin({bottom:80})
}
.tabBar('关注')
}
.width('100%')
.height('100%')
}
}
4. 我的页面Mine.ets
/**
* 我的组件
*/
import SearchHeader from '../record/SearchHeader'
@Component
export default struct Mine{
build() {
Column({space:10}){
// 1.头像
Row(){
Image($r('app.media.user'))
.width('50%')
}
.margin(10)
this.div()
this.message('用户资料:')
this.div()
this.message('收藏')
this.div()
this.message('服务')
this.div()
this.message('设置')
this.div()
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.index_page_background'))
}
@Builder div(){
Row(){
Divider()
.color(Color.Gray)
.strokeWidth(1)
}
}
@Builder message(name:string,){
Row(){
Text(name)
.fontColor(Color.Black)
.fontSize(23)
//.fontWeight(FontWeight.Bold)
Blank()
Image($r('app.media.ic_public_add_norm_filled'))
.fillColor(Color.Gray)
.width('10%')
}
.width('100%')
}
}
五、 问题记录与收获
如何实现分割线?
使用Divder分割线组件,可以使用color()调节分割线的颜色、strokewidth()调节分割线的粗细。