文档管理中心
FAQ应用框架开发UI框架UI界面如何实现List的折叠动画效果

如何实现List的折叠动画效果

可以使用显式动画animateTo结合条件渲染if控制 ListItem内容区域的展开和收起,示例代码如下:

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct ListCollapseExpand {
  4. private numberList: number[] = [0, 1, 2, 3, 4, 5, 6];
  5. @State isContentShow: boolean = true;
  6. @State selectItem: number = 0;
  7. build() {
  8. Column() {
  9. List({ initialIndex: 0 }) {
  10. ForEach(this.numberList, (item: number, index: number) => {
  11. ListItem() {
  12. Column() {
  13. Row() {
  14. Text(item.toString())
  15. Button(this.isContentShow && this.selectItem === item ? 'Collapse' : 'Expand')
  16. .onClick(() => {
  17. this.getUIContext().animateTo({
  18. duration: 300,
  19. onFinish: () => {
  20. console.info('animation end');
  21. }
  22. }, () => {
  23. this.isContentShow = !this.isContentShow;
  24. this.selectItem = item;
  25. })
  26. })
  27. }
  28. .width('100%')
  29. .justifyContent(FlexAlign.SpaceBetween)
  30. // Display the content area only when the current item is selected and is in an expanded state.
  31. if (this.isContentShow && this.selectItem === item) {
  32. Text('This is the content area')
  33. .backgroundColor(Color.Gray)
  34. .width('100%')
  35. .height(100)
  36. }
  37. }
  38. .backgroundColor(0xFFFFFF)
  39. .width('100%')
  40. .padding({
  41. top: 12,
  42. bottom: 12
  43. })
  44. .margin({ top: 10 })
  45. }
  46. }, (item: string) => item.toString())
  47. }
  48. .scrollBar(BarState.Off)
  49. .height('100%')
  50. .width('100%')
  51. }
  52. .backgroundColor(0xF1F3F5)
  53. .padding(12)
  54. }
  55. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词