HarmonyOS鸿蒙Next中list子item高度不固定,如何让其滚动到最底部

发布于 1周前 作者 caililin 来自 鸿蒙OS

HarmonyOS鸿蒙Next中list子item高度不固定,如何让其滚动到最底部 比如聊天页面,初始化的时候有50个聊天内容,这些内容有的是固定高度的,有的富文本,调用scroller.scrollEdge(Edge.Bottom)方法达不到想要的效果,只能滚动一段位置,是否有其他方式

3 回复

可以使用scrollToIndex滚动到数据的最后一个元素,参考如下demo:

@Entry
@Component
struct Index {
  @State dataList: number[] = [1,2,3,4,5,5,6,67,7,7,7,7,7,7,7,7,7,8,9,1,2,3,4,56,7,]
  listScroller: ListScroller = new ListScroller()

  build() {
    Column(){
      List({scroller: this.listScroller}){
        ForEach(this.dataList, (item: number, index) => {
          ListItem(){
            Row(){
              Text(item.toString())
                .fontSize(30)
                .fontColor(Color.Black)
            }
          }
        })
      }
      .width('100%')
      .height('80%')
      Button('滚动到底部')
        .fontColor(Color.Red)
        .fontSize(20)
        .onClick(() => {
          this.listScroller.scrollToIndex(this.dataList.length - 1, true)
        })
    }
  }
}

更多关于HarmonyOS鸿蒙Next中list子item高度不固定,如何让其滚动到最底部的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,如果List的子项高度不固定,且需要滚动到最底部,可以通过以下步骤实现:

  1. 使用List组件时,确保ListlayoutHeight设置为LayoutConfig.MATCH_CONTENT,以便根据内容自动调整高度。
  2. ListItemProvider中,动态计算每个子项的高度,并在onBindComponent方法中进行设置。
  3. 使用ScrollView包裹List,以确保内容超出可视区域时可以滚动。
  4. 在需要滚动到底部时,调用ScrollViewscrollToBottom方法,将内容滚动到最底部。

具体代码示例如下:

import { List, ListItem, ScrollView, LayoutConfig } from '@ohos.arkui';

class CustomList extends List {
  constructor() {
    super();
    this.layoutHeight = LayoutConfig.MATCH_CONTENT;
  }
}

class CustomScrollView extends ScrollView {
  constructor() {
    super();
    this.layoutHeight = LayoutConfig.MATCH_PARENT;
  }

  scrollToBottom() {
    this.scrollTo({ y: this.scrollHeight });
  }
}

const list = new CustomList();
const scrollView = new CustomScrollView();
scrollView.addChild(list);

// 在需要滚动到底部时调用
scrollView.scrollToBottom();

通过上述方法,可以实现List子项高度不固定时,滚动到最底部的功能。

在HarmonyOS鸿蒙Next中,如果List的子项高度不固定,可以通过以下步骤实现滚动到最底部:

  1. 获取List组件:首先获取List组件的引用。
  2. 计算总高度:遍历所有子项,计算它们的总高度。
  3. 滚动到底部:使用scrollTo方法,将List滚动到计算出的总高度位置。

示例代码:

List list = (List) findComponentById(ResourceTable.Id_list);
int totalHeight = 0;
for (int i = 0; i < list.getComponentCount(); i++) {
    totalHeight += list.getComponentAt(i).getHeight();
}
list.scrollTo(totalHeight);

确保在子项布局完成后再执行滚动操作。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!