鸿蒙组件List基本使用方法:改变所点击的item背景色;自动滚动到某item;对齐、点击整行生效、字号、行间距等
·
// import ...
@Entry
@Component
struct Albums {
dataPreferences: preferences.Preferences | null = null;
bookmarkName:string = '';// 书签设置,记录内容为:能唯一区分所点击的item的数据,例如其index
@State select: number = -1;// 上次所点击的ListItem index;记录到preferences中,下回重新进入List页面时,读出并据此自动选定且自动滚动至此
private scrollerForList: Scroller = new Scroller();// 滚动控制器
RelativeContainer() {
// space: 行间距
// initialIndex: 初始化时所需滚动到的index,例如上次点击的item的index
List({ space:8, initialIndex:this.select, scroller: this.scrollerForList }){
// this.albums: List的数据源数组,请自行修改
// Album: albums的元素的自定义数据类型,例如其中有index, name等属性,请自行修改
ForEach(this.albums,(item:Album)=>{
ListItem(){
Row() {
Text(item.name).fontSize(20)// 字号
// 控制点击后该item的背景色切换,即在其它地方修改this.select,就会自动触发该item的背景色改变
.backgroundColor(this.select == item.index?'#32000000':Color.Transparent)
}
}
.width('100%')// 否则点击有内容显示的区域才有效
.align(Alignment.Start)// 否则默认水平居中
.stateStyles({
focused: {// 定义聚焦时的背景色,不知何时发生?
.backgroundColor('#32000000')
},
pressed: {// 定义点击或按住不放时的背景色
.backgroundColor('#32000000')
},
normal: {// 定义正常情况下的背景色
.backgroundColor(Color.Transparent)
}
})
.onClick(() => {
this.dataPreferences?.putSync(this.bookmarkName, this.select = item.index)
// ...
})
})
}
}
}
我需要的业务流程比较简单:(上述代码可以实现)
1、点击某个ListItem后,改变其背景色,并记录书签(最简单就是记录index,但如果以后该List条目增加时,index就不是原来所点的了,这种情况可以自行处理,需要记录的是在Album中其它不依赖index且能唯一区分各item的其它数据,例如对于我这个案例来说是不同album有唯一的path)
2、退出该List页面后,下次进入该List页面时自动滚动到上次所点位置(进入页面时在aboutAppear()中读取preference里上次记录的位置并据此修改this.select的值, initialIndex就会自动生效),且该条目自动改变背景色(.backgroundColor()根据this.select当前值自动执行)。
3、行间距、字号、对齐、点击生效区域是有内容的部分还是整行等设置。
不得不说点击鸿蒙ListItem后改变背景色,以及自动滚动到某个条目的写法很巧妙:你只需在某个其它地方改变this.select的值,系统就替你全操作了,是一种数据改变即可自动驱动相应显示的写法。
如果是安卓或iOS转过来的码农例如我,思路可能会执着于以下思路:得到相应的item id,然后主动执行setBackgroundColor之类的方法;或得到List的id,主动执行scrollTo之类的方法。
更多推荐


所有评论(0)