如何在List组件中分组展示不同种类的数据

数据包含多个种类(例如标题、标题对应的子类等)的子数据,如何根据数据种类为ListItem设置不同的样式。

HarmonyOS
2024-01-20 11:27:18
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
liuxusy

可以通过在List组件中使用ListItemGroup组件来展示Listitem分组,可以单独设置ListItemGroup中的header参数自定义每组的头部组件样式。

代码示例

// xxx.ets 
@Entry 
@Component 
struct ListItemGroupExample { 
  private timetable: TimeTable[] = [ 
    { 
      title: '星期一', 
      projects: ['语文', '数学', '英语'] 
    }, 
    { 
      title: '星期二', 
      projects: ['物理', '化学', '生物'] 
    }, 
    { 
      title: '星期三', 
      projects: ['历史', '地理', '政治'] 
    }, 
    { 
      title: '星期四', 
      projects: ['美术', '音乐', '体育'] 
    } 
  ] 
 
  @Builder 
  itemHead(text: string) { 
    Text(text) 
      .fontSize(20) 
      .backgroundColor(0xAABBCC) 
      .width('100%') 
      .padding(10) 
  } 
 
  @Builder 
  itemFoot(num: number) { 
    Text('共' + num + '节课') 
      .fontSize(16) 
      .backgroundColor(0xAABBCC) 
      .width('100%') 
      .padding(5) 
  } 
 
  build() { 
    Column() { 
      List({ space: 20 }) { 
        ForEach(this.timetable, (item: TimeTable) => { 
          ListItemGroup({ header: this.itemHead(item.title), footer: this.itemFoot(item.projects.length) }) { 
            ForEach(item.projects, (project: string) => { 
              ListItem() { 
                Text(project) 
                  .width('100%') 
                  .height(100) 
                  .fontSize(20) 
                  .textAlign(TextAlign.Center) 
                  .backgroundColor(0xFFFFFF) 
              } 
            }, (item: string) => item) 
          } 
          .divider({ strokeWidth: 1, color: Color.Blue }) // 每行之间的分界线 
        }) 
      } 
      .width('90%') 
      .height('100%') 
      .sticky(StickyStyle.Header | StickyStyle.Footer) 
      .scrollBar(BarState.Off) 
    }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) 
  } 
} 
 
interface TimeTable { 
  title: string; 
  projects: string[]; 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.

效果如图所示:

参考链接

ListItemGroup

分享
微博
QQ
微信
回复
2024-01-21 00:35:58
相关问题
HarmonyOS List展示不全问题
984浏览 • 1回复 待解决
如何在list组件中实现两端渐变
1039浏览 • 1回复 待解决
HarmonyOS HashMap 存各种类数据示例
1021浏览 • 1回复 待解决
HarmonyOS List组件数据更新错误
971浏览 • 0回复 待解决
HarmonyOS list组件数据显示错乱
605浏览 • 1回复 待解决
HarmonyOS List组件动态刷新数据问题
1901浏览 • 1回复 待解决