自定义组件卡顿,怎么办啊?

实现一个自定义的列表,支持竖向滚动和横向滚动,竖向滚动我用了lazyforeach,是不卡的。

横向滚动时,我维护了一个offsetX变量,然后列表的每一项都是一个canvas,当发生滚动时,所有canvas根据offsetX重绘可见部分的内容,实现协同滚动的效果。

依照这个思路实现的控件,发现掉帧率比较高,有90%多。


HarmonyOS
2024-09-29 13:18:35
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

参考demo:

// ScrollListDemoPage.ets  
import { CommonDataSource } from './CommonDataSource'  
import { LeftItemWidth, RightItemWidth, titleCount, pageSize, ListData, listItemData } from './utils'  
import { ItemComponent } from './ItemComponent'  
  
@Entry  
@Component  
struct ScrollListDemoPage {  
  // 头部标题列表,每一列的标题  
  private titleList: string[] = []  
  // 列表数据--展示的内容  
  @State listData: listItemData[] = []  
  // 列表数据垂直滚动  
  verticalScroller: Scroller = new Scroller()  
  // 列表数据横向滚动  
  horizontalScroller: Scroller = new Scroller()  
  // 左侧名称列滚动  
  leftScroller: Scroller = new Scroller()  
  // 头部标题列滚动  
  topScroller: Scroller = new Scroller()  
  // 列表数据横向滚动的距离  
  @State remainOffset: number = 0  
  // 维护一个list控制器数组,用于保存所有横向列表的 ListScroller  
  @State listScrollerArr: ListScroller[] = []  
  // list的开始下标,用来刷新当前屏幕显示的列表区域  
  @State startIndex: number = 0  
  // list的结束下标  
  @State endIndex: number = 0  
  // 列表数据源  
  private dataSource = new CommonDataSource<ListData>()  
  // 头部标题列表数据源  
  headerList = new CommonDataSource<string>()  
  // 实际处理的数据  
  showList: ListData[] = []  
  // 用来模拟上拉加载更多页  
  @State pageNum: number = 1  
  
  aboutToAppear(): void {  
    // 获取数据  
    this.loadData()  
  }  
  
  // 数据处理  
  loadData() {  
    for (let i = 0; i < titleCount; i++) {  
      this.titleList.push('标题名称' + i)  
      let itemData: listItemData = {  
        text: '内容' + i,  
        id: i + this.getRandomVal(),  
      }  
      this.listData.push(itemData)  
    }  
    this.headerList.setData(this.titleList)  
  
    for (let i = 0; i < pageSize; i++) {  
      // 每次获取下一页数据时,需要同步增加list的控制器  
      this.listScrollerArr.push(new ListScroller())  
  
      let listItemData: ListData = new ListData()  
      listItemData.fundName = '基金' + i  
      listItemData.id = '基金' + i  
      listItemData.textDataSource = new CommonDataSource<listItemData>()  
      listItemData.textDataSource.setData(this.listData)  
      this.showList.push(listItemData)  
    }  
    this.dataSource.setData(this.showList)  
  }  
  
  // 数据刷新  
  refreshData() {  
    let listData: listItemData[] = []  
    for (let i = 0; i < titleCount; i++) {  
      let text = '内容' + i + '-' + this.getRandomVal()  
      let itemData: listItemData = {  
        text,  
        id: text  
      }  
      listData.push(itemData)  
    }  
    // 只刷新当前显示在屏幕的数据  
    for (let i = this.startIndex; i <= this.endIndex; i++) {  
      this.showList[i].textDataSource.setData(listData)  
    }  
    this.dataSource.refreshDataByIndex(this.startIndex, this.endIndex, this.showList.slice(this.startIndex, this.endIndex))  
  }  
  
  // 添加数据  
  getNewListPage() {  
    let listData: listItemData[] = []  
    let showList: ListData[] = []  
    for (let i = 0; i < titleCount; i++) {  
      let text = '内容' + i + '-' + this.getRandomVal()  
      let itemData: listItemData = {  
        text,  
        id: text  
      }  
      listData.push(itemData)  
    }  
  
    let s = pageSize* this.pageNum  
    this.pageNum++  
    let e = pageSize* this.pageNum  
    for (let i = s; i < e; i++) {  
      // 每次获取下一页数据时,需要同步增加list的控制器  
      this.listScrollerArr.push(new ListScroller())  
  
      let listItemData: ListData = new ListData()  
      listItemData.fundName = '基金' + i  
      listItemData.id = '基金' + i  
      listItemData.textDataSource = new CommonDataSource<listItemData>()  
      listItemData.textDataSource.setData(listData)  
      showList.push(listItemData)  
    }  
    this.dataSource.pushDataArray(...showList)  
  }  
  
  // 生成1-100的随机数  
  getRandomVal() {  
    const min = 1;  
    const max = 100;  
    const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;  
    return randomInt + ''  
  }  
  
  build() {  
    Column() {  
      // 头部标题  
      this.titleBuilder()  
      Row() {  
        // 左侧列  
        this.leftBuilder()  
        // 右侧列  
        this.rightScroll()  
        Line().height('100%').width(0.5).backgroundColor('#EEEEEE').position({x:LeftItemWidth})  
      }.justifyContent(FlexAlign.Start)  
      .alignItems(VerticalAlign.Top)  
    }.height('100%').justifyContent(FlexAlign.Start).alignItems(HorizontalAlign.Start)  
  }  
  
  // 头部标题  
  @Builder  
  titleBuilder() {  
    Row() {  
      Column() {  
        Text('名称')  
      }  
      .width(LeftItemWidth)  
      .height(60)  
      .backgroundColor(Color.White)  
      .justifyContent(FlexAlign.Center)  
      .alignItems(HorizontalAlign.Start)  
      .padding(10)  
  
      // 分割线  
      Line().height(60).width(0.5).backgroundColor(0xeeeeee)  
      // 头部标题列表  
      List({ scroller: this.topScroller }) {  
        LazyForEach(this.headerList, (item: string, index: number) => {  
          ListItem() {  
            Text(item)  
              .height(60)  
              .width(RightItemWidth)  
              .textAlign(TextAlign.Start)  
              .padding(10)  
              .backgroundColor(0xFFFFFF)  
          }  
        }, (item: string) => item)  
      }  
      .listDirection(Axis.Horizontal)  
      .edgeEffect(EdgeEffect.None)  
      .divider({ strokeWidth: 0.5, color: 0xeeeeee })  
      .scrollBar(BarState.Off)  
      .width('calc(100% - 100vp)').layoutWeight(1)  
      .onScrollFrameBegin((offset: number, state: ScrollState)=>{  
        this.listScrollerArr.forEach((itemScroller) => {  
          itemScroller.scrollTo({xOffset: this.topScroller.currentOffset().xOffset + offset, yOffset:0, animation: false})  
        })  
        return{offsetRemain:offset}  
      })  
    }.height(60).width('100%').justifyContent(FlexAlign.Start)  
  }  
  
  // 左侧列表  
  @Builder  
  leftBuilder(){  
    List({scroller: this.leftScroller }) {  
      LazyForEach(this.dataSource, (item: ListData, index: number) => {  
        ListItem() {  
          Column(){  
            Text(item.fundName)  
              .width(LeftItemWidth)  
              .height('100%')  
              .textAlign(TextAlign.Center)  
              .backgroundColor(0xFFFFFF)  
              .layoutWeight(1)  
            Line().width("100%").height(0.5).backgroundColor(0xeeeeee)  
          }  
        }  
        .height(100)  
      },(item: ListData, index: number) => item.fundName! + index + item.id)  
    }  
    .listDirection(Axis.Vertical)  
    .scrollBar(BarState.Off)  
    .edgeEffect(EdgeEffect.None)  
    .height('calc(100% - 60vp)')  
    .width(LeftItemWidth)  
    .visibility(Visibility.Visible)  
    .onScrollFrameBegin((offset: number, state: ScrollState) => {  
      this.verticalScroller.scrollTo({  
        xOffset: 0,  
        yOffset: this.leftScroller.currentOffset().yOffset + offset,  
        animation: false  
      })  
      return { offsetRemain: offset }  
    })  
  }  
  
  // 右侧列表  
  @Builder  
  rightScroll(){  
    Scroll(this.horizontalScroller) {  
      List({ initialIndex: 0, scroller: this.verticalScroller }) {  
        LazyForEach(this.dataSource, (item: ListData, index: number) => {  
          ListItem() {  
            ItemComponent({  
              scroller: this.listScrollerArr[index],  
              data: item,  
              scrollCallBack:(value)=>{  
                this.topScroller.scrollTo({xOffset:value, yOffset:0, animation: false})  
                this.listScrollerArr.forEach((itemScroller) => {  
                  if(itemScroller != this.listScrollerArr[index]){  
                    itemScroller.scrollTo({xOffset: value,yOffset:0, animation: false})  
                  }  
                })  
              },  
              remainOffsetCallBack:(value)=>{  
                this.remainOffset = value  
              },  
            })  
          }  
        })  
      }  
      .cachedCount(2)  
      .flingSpeedLimit(2000)  
      .listDirection(Axis.Vertical)  
      .scrollBar(BarState.Off)  
      .edgeEffect(EdgeEffect.None)  
      .nestedScroll({ scrollForward: NestedScrollMode.PARENT_FIRST, scrollBackward: NestedScrollMode.PARENT_FIRST })  
      .onScrollFrameBegin((offset: number, state: ScrollState) => {  
        this.leftScroller.scrollTo({  
          xOffset: this.remainOffset,  
          yOffset: this.verticalScroller.currentOffset().yOffset + offset,  
          animation: false  
        })  
        return { offsetRemain: offset }  
      })  
      .onScroll(()=>{  
        this.listScrollerArr.forEach((itemScroller) => {  
          itemScroller.scrollTo({xOffset: this.remainOffset,yOffset:0, animation: false})  
        })  
      })  
      .onScrollIndex((start: number, end: number) => {  
        this.startIndex = start  
        this.endIndex = end  
      })  
      .onReachEnd(() => {  
        // 模拟上拉加载更多  
        setTimeout(() => {  
          this.getNewListPage()  
        }, 1000)  
      })  
      .onReachStart(() => {  
        // 模拟下拉刷新  
        setTimeout(() => {  
          this.refreshData()  
        }, 1000)  
      })  
  
    }  
    .position({ x: LeftItemWidth, y: 0 })  
    .onScroll((scrollOffset: number, scrollState: ScrollState) => {  
      this.topScroller.scrollTo({ xOffset: this.horizontalScroller.currentOffset().xOffset, yOffset: 0, animation: false })  
    })  
    .scrollBar(BarState.Off)  
    .edgeEffect(EdgeEffect.None)  
    .scrollable(ScrollDirection.Horizontal)  
    .backgroundColor(0xDCDCDC)  
    .height('calc(100% - 60vp)')  
    .width('calc(100% - 100vp)')  
  }  
}  
  
// ItemComponent.ets  
import { RightItemWidth, listItemData, ListData } from './utils'  
  
@Component  
export struct ItemComponent {  
  private scroller?: ListScroller = undefined  
  private scrollCallBack?: (param: number) => void  
  private remainOffsetCallBack?: (param: number) => void  
  @ObjectLink data: ListData  
  build() {  
    Column() {  
      List({ scroller: this.scroller }) {  
        LazyForEach(this.data.textDataSource, (item: listItemData, index: number) => {  
          ListItem() {  
            Text(item.text)  
              .height('100%')  
              .width('100%')  
              .textAlign(TextAlign.Start)  
              .padding(10)  
              .backgroundColor(0xFFFFFF)  
              .fontColor('#66000000')  
              .maxLines(1)  
              .textOverflow({overflow: TextOverflow.Ellipsis})  
          }  
          .width(RightItemWidth)  
        }, (item: listItemData, index: number) => JSON.stringify(item) + index + '')  
      }  
      .cachedCount(4)  
      .height('100%')  
      .width('100%')  
      .layoutWeight(1)  
      .listDirection(Axis.Horizontal)  
      .scrollBar(BarState.Off)  
      .nestedScroll({  
        scrollForward: NestedScrollMode.PARENT_FIRST,  
        scrollBackward: NestedScrollMode.PARENT_FIRST  
      })  
      .divider({ strokeWidth: 0.5, color: 0xeeeeee })  
      .edgeEffect(EdgeEffect.None)  
      .onScroll(() => {  
        if (this.remainOffsetCallBack) {  
          this.remainOffsetCallBack(this.scroller!.currentOffset().xOffset)  
        }  
      })  
      .onScrollFrameBegin((offset: number, state: ScrollState) => {  
        if (this.scrollCallBack) {  
          this.scrollCallBack(this.scroller!.currentOffset().xOffset + offset)  
        }  
        return { offsetRemain: offset }  
      })  
      Line().width("100%").height(0.5).backgroundColor(0xeeeeee)  
    }.height(100)  
  }  
}  
  
// utils.ets  
  
import { CommonDataSource } from './CommonDataSource'  
  
export const LeftItemWidth = 100  
export const RightItemWidth = 100  
// 标题列的个数  
export const titleCount = 30  
// 每页的基金数量  
export const pageSize = 20  
// 基金的总数  
export const totalCount = 400  
  
@Observed  
export class listItemData {  
  text: string = ''  
  id: string = ''  
}  
  
@Observed  
export class ListData {  
  id: string = ''  
  fundName: string = ''  
  textDataSource: CommonDataSource<listItemData> = new CommonDataSource<listItemData>()  
}  
  
// CommonDataSource.ets  
  
export class CommonDataSource<T> implements IDataSource {  
  private listeners: DataChangeListener[] = [];  
  protected originDataArray: T[] = [];  
  
  totalCount(): number {  
    return this.originDataArray.length;  
  }  
  
  getAllData(): T[] {  
    return this.originDataArray  
  }  
  
  getData(index: number) {  
    return this.originDataArray[index];  
  }  
  
  addData(index: number, data: T): void {  
    this.originDataArray.splice(index, 0, data);  
    this.notifyDataAdd(index);  
  }  
  
  pushData(data: T): void {  
    this.originDataArray.push(data);  
    this.notifyDataAdd(this.originDataArray.length - 1);  
  }  
  
  pushDataArray(...items: T[]): void {  
    for (let data of items) {  
      this.originDataArray.push(data);  
      this.notifyDataAdd(this.originDataArray.length - 1);  
    }  
  }  
  
  deleteDataUseContent(data: T): void {  
    let delIndex: number = -1  
    for (let index = 0; index < this.originDataArray.length; index++) {  
      const element = this.originDataArray[index];  
      if (data === element) {  
        delIndex = index  
      }  
    }  
    if (delIndex != -1) {  
      this.deleteData(delIndex)  
    }  
  }  
  
  deleteData(index: number): void {  
    this.originDataArray.splice(index, 1);  
    this.notifyDataDelete(index);  
  }  
  
  clear() {  
    this.originDataArray.splice(0, this.originDataArray.length)  
    this.listeners.forEach(listener => {  
      listener.onDataDelete(0)  
    })  
  }  
  
  setData(dataArray?: T[]) {  
    if (dataArray) {  
      this.originDataArray = dataArray  
    } else {  
      this.originDataArray = []  
    }  
    this.notifyDataReload()  
  }  
  
  refreshDataByIndex(start: number, end: number, dataArray: T[]) {  
    this.originDataArray.splice(start, end - start, ...dataArray);  
    this.notifyDataReload()  
  }  
  
  changeData(index: number, data: T): void {  
    this.originDataArray.splice(index, 1, data);  
    this.notifyDataChange(index);  
  }  
  
  registerDataChangeListener(listener: DataChangeListener): void {  
    if (this.listeners.indexOf(listener) < 0) {  
      this.listeners.push(listener);  
    }  
  }  
  
  unregisterDataChangeListener(listener: DataChangeListener): void {  
    const pos = this.listeners.indexOf(listener);  
    if (pos >= 0) {  
      this.listeners.splice(pos, 1);  
    }  
  }  
  
  notifyDataReload() {  
    this.listeners.forEach(listener => {  
      listener.onDataReloaded();  
    })  
  }  
  
  notifyDataAdd(index: number) {  
    this.listeners.forEach(listener => {  
      listener.onDataAdd(index);  
    })  
  }  
  
  notifyDataMove(from: number, to: number) {  
    this.listeners.forEach(listener => {  
      listener.onDataMove(from, to);  
    })  
  }  
  
  notifyDataDelete(index: number) {  
    this.listeners.forEach(listener => {  
      listener.onDataDelete(index);  
    })  
  }  
  
  notifyDataChange(index: number) {  
    this.listeners.forEach(listener => {  
      listener.onDataChange(index);  
    })  
  }  
}
分享
微博
QQ
微信
回复
2024-09-29 18:23:54
相关问题
Web嵌套滑动怎么办
153浏览 • 1回复 待解决
自定义文件模板失效怎么办
288浏览 • 1回复 待解决
最新RNOH启动报错 ,该怎么办
917浏览 • 1回复 待解决
for .in 语法不支持,该怎么办
696浏览 • 1回复 待解决
运行应用提示如下内容该怎么办
2271浏览 • 1回复 待解决
安装动态库失败,该怎么办
523浏览 • 1回复 待解决
怎么办
714浏览 • 1回复 待解决
模拟器不能启动该怎么办
291浏览 • 1回复 待解决
studio编译经常报错该怎么办
423浏览 • 1回复 待解决
字符串资源引用出错,该怎么办
701浏览 • 1回复 待解决
状态栏设置颜色失效该怎么办
1821浏览 • 1回复 待解决
redis 内存满了怎么办
3650浏览 • 3回复 待解决
有谁知道asset api调用失败怎么办?
1641浏览 • 1回复 待解决
JAVA卡片怎么自定义组件
6383浏览 • 1回复 待解决
无法使用hdc命令怎么办
3051浏览 • 1回复 待解决
多个模块依赖出现冲突,怎么办
54浏览 • 1回复 待解决
自定义组件嵌套子组件
9333浏览 • 3回复 待解决
中奖码忘了保存怎么办
5532浏览 • 1回复 待解决
Gradle的依赖缓存被损坏怎么办
14095浏览 • 5回复 待解决
提问
该提问已有0人参与 ,帮助了0人