HarmonyOS鸿蒙Next中持久化数据时Slider的显示问题

HarmonyOS鸿蒙Next中持久化数据时Slider的显示问题

页面代码如下:

import IndexFontSizePanle from '../views/IndexFontSizePanel'
PersistentStorage.PersistProp("fontSize",20)
@Entry
@Component
struct PreferPage {
  @Provide fontSize: number = AppStorage.Get("fontSize")
  @State showPanel:boolean = true


  aboutToDisappear(){
    AppStorage.Set("fontSize",this.fontSize)
  }

  build() {
    Column(){
      Row(){
        Text("首选项")
          .fontSize(35)
          .fontWeight(FontWeight.Bold)
        Blank()
        Image($r('app.media.ic_public_settings'))
          .width(35)
          .onClick(()=>{
              this.showPanel = !this.showPanel
          })
      }
      .width("90%")
      Text("鸿蒙OS遥遥领先"+this.fontSize)
        .fontSize(this.fontSize)
        .width("100%")
        .height("85%")
        .fontWeight(FontWeight.Bolder)
        .textAlign(TextAlign.Center)
      if(this.showPanel){
          IndexFontSizePanle()
            .layoutWeight(1)
      }

    }
    .width("100%")
    .height("100%")
  }
}

IndexFontSizePanle代码如下:

@Component
export default struct IndexFontSizePanle{
  @Consume fontSize:number
  fontSizeLabel:object = {
    14:"小",
    16:"标准",
    18:"大",
    20:"特大"
  }
  aboutToAppear(){

  }
  build(){
    Column(){
        Text(this.fontSizeLabel[this.fontSize])
          .fontSize(20)
        Row({space:5}){
          Text("A")
            .fontSize(14)
            .fontWeight(FontWeight.Bold)
          Slider({max:20,min:14,value:this.fontSize,step:2})
            .showSteps(true)
            .trackThickness(6)
            .layoutWeight(1)
            .onChange(val=>{
              this.fontSize = val
            })
          Text("A")
            .fontSize(20)
            .fontWeight(FontWeight.Bold)
        }
        .width("100%")
      .padding({left:15,right:15})
    }
    .backgroundColor("#fff3f6f4")
    .border({ radius:10 })
  }
}

设置字体大小后,关闭APP,再打开是可以获得最后设置的值。但唯一有问题的就是Slider的滑块没法定位到相应值位置上。但fontSize变量的值是正确的。就是Slider无法正确显示。请问这该如何解决


更多关于HarmonyOS鸿蒙Next中持久化数据时Slider的显示问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中持久化数据时Slider的显示问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,持久化Slider的显示状态时,建议使用PersistentStorageAppStorage进行数据保存与恢复。通过绑定Slider的value属性到持久化存储,确保应用重启后能正确恢复Slider的位置。同时,注意监听Slider的onChange事件,实时更新存储值,保证数据一致性。例如:

@StorageLink('sliderValue') sliderValue: number = 50;

Slider({
  value: this.sliderValue,
  onChange: (value: number) => {
    this.sliderValue = value;
  }
})

这样可以确保Slider的状态在应用重启后正确显示。

回到顶部