HarmonyOS NEXT 如何在一个page里面,然后通过点击一个按钮,显示加载不同的view ?

阅读 621
avatarAI BotBETA
在 HarmonyOS NEXT 中,你可以通过以下步骤在一个 Page 中通过点击按钮来显示加载不同的 View:

1. **定义不同的 View**:首先,你需要在你的资源文件中定义好你想要显示的不同的 View。这可以通过 XML 布局文件或者在代码中动态创建 View 来实现。

2. **设置按钮点击事件**:在你的 Page 中,找到你想要用来触发 View 切换的按钮,并为其设置点击事件监听器。

3. **实现 View 切换逻辑**:在按钮的点击事件处理函数中,根据点击事件来切换显示的 View。这可以通过修改当前 Page 的布局或者通过 Fragment(如果 HarmonyOS NEXT 支持类似 Android 的 Fragment 机制)来实现。

4. **更新 UI**:最后,确保你的 UI 得到了更新,以显示新的 View。

具体实现可能会依赖于 HarmonyOS NEXT 的 SDK 和 API,因此建议查阅相关的官方文档和示例代码以获取更详细的信息。
1 个回答

你可以参考如下代码:

import { BusinessError } from "@ohos.base"; 
import { HashMap } from '@kit.ArkTS'; 
import map from '@hms.core.map.map'; 
 
@Component 
struct Child { 
  @Builder 
  customBuilder() { 
  } 
 
  // 使用父组件@Builder装饰的方法初始化子组件@BuilderParam 
  @BuilderParam customBuilderParam: () => void = this.customBuilder; 
 
  build() { 
    Column() { 
      this.customBuilderParam() 
 
    } 
  } 
} 
 
@Entry 
@Component 
struct Index45 { 
  @State message: string = 'Hello World'; 
  @State keys: number = 1 
 
  @Builder 
  component1() { 
    Column() { 
      Text('component0') 
        .width(100) 
        .backgroundColor(Color.Red) 
    } 
    .width('100%') 
  } 
 
  @Builder 
  component2() { 
    Column() { 
      Text('component1') 
        .width(100) 
        .backgroundColor(Color.Red) 
    } 
    .width('100%') 
  } 
 
  @Builder 
  component3() { 
    Column() { 
      Text('component2') 
        .width(100) 
        .backgroundColor(Color.Red) 
    } 
    .width('100%') 
  } 
 
  build() { 
 
    Column({ space: 30 }) { 
      Text('显示component1') 
        .fontSize(20) 
        .fontWeight(FontWeight.Bold) 
        .onClick(() => { 
          this.keys = 0 
        }) 
      Text('显示component2') 
        .fontSize(20) 
        .fontWeight(FontWeight.Bold) 
        .onClick(() => { 
          this.keys = 1 
        }) 
      Text('显示component3') 
        .fontSize(20) 
        .fontWeight(FontWeight.Bold) 
        .onClick(() => { 
          this.keys = 2 
 
        }) 
 
      if (this.keys === 0) { 
        Child({ customBuilderParam: this.component1 }) 
      } else if (this.keys === 1) { 
        Child({ customBuilderParam: this.component2 }) 
      } else { 
        Child({ customBuilderParam: this.component3 }) 
      } 
    } 
    .height('100%') 
    .width('100%') 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进