繼續先放一下效果圖
然后繼續上一篇文章的內容,上一次我們講到如何去獲取每個人名字的第一個字,接下來講一下如何設置每個名字之前的那個圓的背景色
先放一下代碼:
getAvatarColor(name:string):string{
const colors = [
'#FF9AA2', '#FFB7B2', '#FFDAC1', '#E2F0CB', '#B5EAD7',
'#C7CEEA', '#A8E6CF', '#FFD3A5', '#FD9644', '#9BB5FF',
'#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9', '#F8C471'
];
const index = name.charCodeAt(0) % colors.length;
return colors[index];
}
name.charCodeAt(0) 方法用于獲取 name 字符串的第一個字符的 Unicode 編碼。例如,如果 name 是 "Apple",那么 name.charCodeAt(0) 將返回字符 'A' 的 Unicode 編碼(65)。
colors.length 表示 colors 數組的長度,這里是 15。
% 是取模運算符,用于計算 name.charCodeAt(0) 除以 colors.length 的余數。這個余數將作為 colors 數組的索引,確保索引值在 0 到 colors.length - 1 的范圍內。例如,如果 name.charCodeAt(0) 是 65,colors.length 是 15,那么 65 % 15 的結果是 5,這意味著 index 的值為 5。所以說,每一個字符都能找到其專屬的一個顏色,而不用搞隨機數,也能保證視覺效果的一致性。
然后要先設置基本的UI,通過List + ListItemGroup + ListItem來實現,一般項目里我們很少用到ListItemGroup,但是因為這里我們在滾動的時候,是按照首字母為一個組進行滾動的,并且每一組上面都有一個字母作為“標題”,所以使用ListItemGroup更加方便,代碼如下:
List({scroller:this.scroller}){
//聯系人列表
ForEach(this.contactListArr,(val:Contact)= >{
ListItemGroup({header:this.HeaderGroupItem(val.group)}){
ForEach(val.namesList,(name:string)= >{
ListItem(){
Row(){
//頭像
Column(){
Text(this.getInitial(name))
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#ffffff')
}.width(45).height(45).backgroundColor(this.getAvatarColor(name)).borderRadius(22.5).justifyContent(FlexAlign.Center).margin({right:16}).shadow({
radius:4,color:'#00000015',offsetX:0,offsetY:2
})
//姓名
Text(name)
.fontSize(16)
.fontColor('#1a1a1a')
.layoutWeight(1)
//右箭頭
Text(' >')
.fontSize(16)
.fontColor('#c7c7cc')
}.width('100%').padding({left:20,right:20,top:12,bottom:12}).alignItems(VerticalAlign.Center).backgroundColor('#ffffff').onClick(()= >{
console.log(`點擊了聯系人: ${name}`)
})
}
})
}
})
}.backgroundColor('#f5f5f5').divider({
strokeWidth:0.5,color:'#f0f0f0',startMargin:81,endMargin:20
}).onScrollIndex((start)= >{
this.currentIndex = start;
}).layoutWeight(1)
接下來是AlphabetIndexer組件,我們先貼一下代碼,然后再詳細講解里面的各個屬性
AlphabetIndexer({arrayValue:this.alphabets,selected:this.currentIndex})
.autoCollapse(false)
.selectedColor('#007AFF')
.itemSize(20)
.popupBackground('#ffffff')
.usingPopup(true)
.alignStyle(IndexerAlign.Right)
.popupFont({size:24,weight:FontWeight.Medium})
.selectedFont({size:14,weight:FontWeight.Medium})
.font({size:12})
.itemBorderRadius(10)
.popupPosition({x:30,y:0})
.margin({right:12})
.popupItemBorderRadius(8)
.popupSelectedColor('#007AFF')
.popupUnselectedColor('#8e8e93')
.onSelect((index)= >{
this.scroller.scrollToIndex(index)
})
autoCollpase是是否自適應折疊模式,在api12以后,這個值默認為true,即自適應折疊模式,因為我們現在是26個英文字母,所以按照文檔里的說法,是會默認折疊的。
usingPopup代表的是是否默認顯示彈窗,也就是比如說你點了右邊的A以后,會有一個彈窗來顯示你當前點擊的是“A”
popupPosition就是代表的這個彈窗的位置,具體位置是相對于索引條上邊框中點的位置。但是這里和普通的position有點不太一樣……普通的坐標軸是往左往上是負值,這里的是往左和往下是正值
然后是onSelect,也就是選中后,那么讓滾動的控制器滾動到對應的ListItemGroup即可,因為26個英文字母都有自己對應的Group
最后,要注意這個List組件和AlphabetIndexer組件需要放在同一個stack組件里,采用堆疊容器
審核編輯 黃宇
-
Unicode
+關注
關注
0文章
25瀏覽量
12724 -
鴻蒙
+關注
關注
59文章
2594瀏覽量
43963
發布評論請先 登錄
評論