前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >鸿蒙-元服务-坚果派-第四章 基础控件

鸿蒙-元服务-坚果派-第四章 基础控件

作者头像
红目香薰
发布2025-02-20 07:47:43
发布2025-02-20 07:47:43
4600
代码可运行
举报
文章被收录于专栏:CSDNToQQCodeCSDNToQQCode
运行总次数:0
代码可运行

作者简介:大数据领域优质创作者、CSDN博客专家 、阿里云博客专家、华为云课堂认证讲师、华为云社区云享专家、坚果派社区成员、具有10余年横向开发经验,全国教师技能大赛获奖教师,现从事于大学计算机领域教育工作。 主要内容:人工智能与大数据、Java、Python、C#、PHP、ASP.NET、ArkTS、FAQ、简历模板、学习资料、面试题库、就业指导等。 初心目标:持续输出,为技术人创造更多的价值。

第四章 基础控件

1、创建文本(Text)

Text是文本组件,通常用于展示用户视图,如显示文章的文字。

Text可通过以下两种方式来创建:

1、直接创建:

Text('我是一段文本')

2、引用Resource资源,资源路径为【/resources/base/element/string.json】

Text($r('app.string.module_desc'))

添加子组件

Span只能作为Text和RichEditor组件的子组件显示文本内容。可以在一个Text内添加多个Span来显示一段信息,会取消Text显示文字。

Span组件需要写到Text组件内,单独写Span组件不会显示信息,Text与Span同时配置文本内容时,Span内容覆盖Text内容。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct ShowText {
  build() {
    Column() {
      Text("坚果派-红目香薰") {
        Span("鸿蒙-坚果派")
      }.fontSize(30)
      .margin({ top: 100 })
      .border({width:2,style:BorderStyle.Solid,color:Color.Black})
      .width('80%')
    }
  }
}
文本样式

设置文本装饰线及颜色,通过decoration设置文本装饰线及颜色。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct ShowText {
  build() {
    Column() {
      Text("坚果派-红目香薰") {
        Span("陌上") .decoration({ type: TextDecorationType.LineThrough, color: Color.Red })
        Span("人如") .decoration({ type: TextDecorationType.Underline, color: Color.Black })
        Span("玉") .decoration({ type: TextDecorationType.Overline, color: Color.Gray })
      }.fontSize(30)
      .margin({ top: 100 })
      .border({width:2,style:BorderStyle.Solid,color:Color.Black})
      .width('80%')
      .height('50%')
    }
  }
}
大小写转换

通过textCase设置文字一直保持大写或者小写状态。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct ShowText {
  build() {
    Column() {
      Text("坚果派-红目香薰") {
        Span("i ").textCase(TextCase.UpperCase)
        Span(" Love").textCase(TextCase.LowerCase)
        Span(" You").textCase(TextCase.UpperCase)
      }
      .fontSize(30)
      .margin({ top: 100 })
      .border({ width: 2, style: BorderStyle.Solid, color: Color.Black })
      .width('80%')
      .height('50%')
    }
  }
}
文字事件添加

由于Span组件无尺寸信息,事件仅支持添加点击事件onClick。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct ShowText {
  build() {
    Column() {
      Text("坚果派-红目香薰") {
        Span("i ").textCase(TextCase.UpperCase).onClick(()=>{
          console.info('陌上人如玉')
        })
        Span(" Love").textCase(TextCase.LowerCase).onClick(()=>{
          console.info('君子世无双')
        })
        Span(" You").textCase(TextCase.UpperCase).onClick(()=>{
          console.info('星光不问赶路人。')
        })
      }
      .fontSize(30)
      .margin({ top: 100 })
      .border({ width: 2, style: BorderStyle.Solid, color: Color.Black })
      .width('80%')
      .height('50%')
    }
  }
}
自定义文本样式

通过textAlign属性设置文本对齐样式。

通过textOverflow属性控制文本超长处理,textOverflow需配合maxLines一起使用(默认情况下文本自动折行)。

通过lineHeight属性设置文本行高。

通过baselineOffset属性设置文本基线的偏移量。

通过letterSpacing属性设置文本字符间距。

通过minFontSize与maxFontSize自适应字体大小,minFontSize设置文本最小显示字号,maxFontSize设置文本最大显示字号,minFontSize与maxFontSize必须搭配同时使用,以及需配合maxline或布局大小限制一起使用,单独设置不生效。

通过copyOption属性设置文本是否可复制粘贴。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct ShowText {
  build() {
    Column() {
      Text() {
        Span("昼短苦夜长,")
      }.textAlign(TextAlign.Center)// Start Center End
      .fontSize(50)
      .margin({ top: 100 })
      .border({ width: 2, style: BorderStyle.Solid, color: Color.Black })
      .width('70%')
      .textOverflow({ overflow: TextOverflow.None })
      .maxLines(1)
      .lineHeight(30)
      .baselineOffset(0)
      .letterSpacing(5)

      Text() {
        Span("何不秉烛游?")
      }
      .fontSize(50)
      .margin({ top: 100 })
      .border({ width: 2, style: BorderStyle.Solid, color: Color.Black })
      .width('80%')
      .textOverflow({ overflow: TextOverflow.Ellipsis })
      .maxLines(1)
      .lineHeight(100)
      .baselineOffset(50)
      .letterSpacing(50)

      Text() {
        Span("山河远阔,人间星河,无一是你,无一不是你。")
      }
      .fontSize(30)
      .margin({ top: 100 })
      .border({ width: 2, style: BorderStyle.Solid, color: Color.Black })
      .width('80%')
      .textOverflow({ overflow: TextOverflow.MARQUEE })
      .maxLines(1)
      .baselineOffset(-50)
      .letterSpacing(5)
      .maxFontSize(50)
      .minFontSize(5)
      .copyOption(CopyOptions.InApp)
    }
  }
}
新闻示例
代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct NewsPage {
  build() {
    Column() {
      Row() {
        Text("1").fontSize(14).fontColor(Color.Red).margin({ left: 10, right: 10 })
        Text("河北文旅杀疯了")
          .fontSize(12)
          .fontColor(Color.Blue)
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
          .fontWeight(300)
        Text("爆")
          .margin({ left: 6 })
          .textAlign(TextAlign.Center)
          .fontSize(10)
          .fontColor(Color.White)
          .fontWeight(600)
          .backgroundColor(0x770100)
          .borderRadius(5)
          .width(15)
          .height(14)
      }.width('100%').margin(5)

      Row() {
        Text("2").fontSize(14).fontColor(Color.Red).margin({ left: 10, right: 10 })
        Text("金秋以来,京津冀雾霾天气多的原因具体说明")
          .fontSize(12)
          .fontColor(Color.Blue)
          .fontWeight(300)
          .constraintSize({ maxWidth: 200 })
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
        Text("热")
          .margin({ left: 6 })
          .textAlign(TextAlign.Center)
          .fontSize(10)
          .fontColor(Color.White)
          .fontWeight(600)
          .backgroundColor(0xCC5500)
          .borderRadius(5)
          .width(15)
          .height(14)
      }.width('100%').margin(5)

      Row() {
        Text("3").fontSize(14).fontColor(Color.Orange).margin({ left: 10, right: 10 })
        Text("石家庄北城国际探索到了百亿储量的原油")
          .fontSize(12)
          .fontColor(Color.Blue)
          .fontWeight(300)
          .maxLines(1)
          .constraintSize({ maxWidth: 200 })
          .textOverflow({ overflow: TextOverflow.Ellipsis })
        Text("热")
          .margin({ left: 6 })
          .textAlign(TextAlign.Center)
          .fontSize(10)
          .fontColor(Color.White)
          .fontWeight(600)
          .backgroundColor(0xCC5500)
          .borderRadius(5)
          .width(15)
          .height(14)
      }.width('100%').margin(5)

      Row() {
        Text("4").fontSize(14).fontColor(Color.Grey).margin({ left: 10, right: 10 })
        Text("霸道总裁爱上三无的她?")
          .fontSize(12)
          .fontColor(Color.Blue)
          .fontWeight(300)
          .constraintSize({ maxWidth: 200 })
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
      }.width('100%').margin(5)
    }.width('100%')
  }
}

2、文本输入(TextInput/TextArea)

TextInput、TextArea是输入框组件,通常用于响应用户的输入操作,比如评论区的输入、聊天框的输入、表格的输入等,也可以结合其它组件构建功能页面,例如登录注册页面。

创建输入框

TextInput为单行输入框、TextArea为多行输入框。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct TextInputPage {
  build() {
    Column() {
      TextInput({ placeholder: "请输入昵称", })
        .fontSize(28)
        .margin({ top: 100 })
        .placeholderFont({ size: 28 })

      TextArea({ text: "情字何解,怎么落笔都不对!\n 怎奈向,随流水,思念悠长。" })
        .width(300)
        .margin({ top: 50 })
    }
  }
}
设置输入框类型

TextInput有9种可选类型,分别为Normal基本输入模式、Password密码输入模式、Email邮箱地址输入模式、Number纯数字输入模式、PhoneNumber电话号码输入模式、USER_NAME用户名输入模式、NEW_PASSWORD新密码输入模式、NUMBER_PASSWORD纯数字密码输入模式、NUMBER_DECIMAL带小数点的数字输入模式。通过type属性进行设置:

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct TextInputPage {
  build() {
    Column() {
      TextInput({ placeholder: "请输入昵称", })
        .fontSize(28)
        .margin({ top: 100 })
        .placeholderFont({ size: 28 })
      TextInput({ placeholder: "请输入密码", }).type(InputType.Password)
      TextInput({ placeholder: "请输入新密码", }).type(InputType.NEW_PASSWORD)
      TextInput({ placeholder: "请输入纯数字密码", }).type(InputType.NUMBER_PASSWORD)
      TextInput({ placeholder: "请输入数字", }).type(InputType.Number)
      TextInput({ placeholder: "请输入π值", }).type(InputType.NUMBER_DECIMAL)
      TextInput({ placeholder: "请输入邮箱", }).type(InputType.Email)
      TextInput({ placeholder: "请输入手机号", }).type(InputType.PhoneNumber)

      TextArea({ text: "情字何解,怎么落笔都不对!\n 怎奈向,随流水,思念悠长。" })
        .width(300)
        .margin({ top: 50 })
    }
  }
}
添加事件

文本框主要用于获取用户输入的信息,把信息处理成数据进行上传,绑定onChange事件可以获取输入框内改变的内容。用户也可以使用通用事件来进行相应的交互操作。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct TextInputPage {
  build() {
    Column() {
      TextInput({ placeholder: "请输入昵称", })
        .fontSize(28)
        .margin({ top: 100 })
        .placeholderFont({ size: 28 })
        .onChange(()=>{
          console.log("值被修改了。")
        })
        .onFocus(()=>{
          console.log("被获取了焦点");
        })

      TextInput({ placeholder: "请输入密码", }).type(InputType.Password)
      TextInput({ placeholder: "请输入新密码", }).type(InputType.NEW_PASSWORD)
      TextInput({ placeholder: "请输入纯数字密码", }).type(InputType.NUMBER_PASSWORD)
      TextInput({ placeholder: "请输入数字", }).type(InputType.Number)
      TextInput({ placeholder: "请输入π值", }).type(InputType.NUMBER_DECIMAL)
      TextInput({ placeholder: "请输入邮箱", }).type(InputType.Email)
      TextInput({ placeholder: "请输入手机号", }).type(InputType.PhoneNumber)

      TextArea({ text: "情字何解,怎么落笔都不对!\n 怎奈向,随流水,思念悠长。" })
        .width(300)
        .margin({ top: 50 })
    }
  }
}
登录窗体示例
代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct LoginPage {
  @State userName:string = "";
  @State passWorld:string = "";
  build() {
    Column() {
      Row() {
        Text("账号:").fontSize(22).width('20%')
        TextInput({ placeholder: "请输入账号" ,text:this.userName}).fontSize(26)
          .onChange((EnterKeyType)=>{
            this.userName = EnterKeyType;
          }).width('80%')
      }
      Blank()
      Row() {
        Text("密码:").fontSize(22).width('20%')
        TextInput({ placeholder: "请输入密码" ,text:this.passWorld})
          .type(InputType.Password).fontSize(26)
          .onChange((EnterKeyType)=>{
            this.passWorld = EnterKeyType;
          }).width('80%')
      }
      Blank()
      Row(){
        Button("登录").width('80%').onClick(()=>{
          if(this.userName == "admin" && this.passWorld == "123456"){
            console.log("登录测试成功");
          }else{
            console.log("账号密码有误");
          }
        })
      }
    }.width('100%').height('30%')
    .justifyContent(FlexAlign.Center)
    .margin({top:100})
  }
}
键盘避让
代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct ScrollTestPage{
  infos: string[] = ['1', '2', '3', '4', '5', '6', '7']
  build() {
    Scroll() {
      Column() {
        ForEach(this.infos, (placeholder: string) => {
          TextInput({ placeholder: '输入框 ' + placeholder })
            .margin(30)
        })
      }
    }
  }
}

3、富文本(RichEditor)

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct RichEditorPage {
  controller: RichEditorController = new RichEditorController();
  options: RichEditorOptions = { controller: this.controller };
  build() {
    Column(){
      RichEditor(this.options)
        .onReady(() => {
          this.controller.addTextSpan('创建不使用属性字符串构建的\nRichEditor\n富文本编辑器组件。', {
            style: {
              fontColor: Color.Black,
              fontSize: 15
            }
          })
        })
        .border({width:2,style:BorderStyle.Solid,color:Color.Black})
        .margin({top:200})
    }
  }
}
添加文本与获取信息
代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct RichEditorPage {
  controller: RichEditorController = new RichEditorController();
  options: RichEditorOptions = { controller: this.controller };
  @State show:string="";
  build() {
    Column() {
      RichEditor(this.options)
        .onReady(() => {
          this.controller.addTextSpan('创建不使用属性字符串构建的 RichEditor 富文本编辑器组件。', {
            style: {
              fontColor: Color.Black,
              fontSize: 15
            }
          })
        })
        .border({ width: 2, style: BorderStyle.Solid, color: Color.Black })
        .width('100%')
        .height('10%')
        .margin({ top: 50 })

      Button("添加信息").onClick(() => {
        this.controller.addTextSpan('新添加一段文字。')
      }).width(200)
        .height(70)
        .margin({ top: 20 })
      Button("获取信息").onClick(() => {
        this.show = "";
        this.show = JSON.stringify(this.controller.getSpans()[0]["value"]);
      })
        .width(200)
        .height(70)
        .margin({ top: 20 })
      Text(this.show)
    }
  }
}

4、图标小符号 (SymbolGlyph/SymbolSpan)

SymbolGlyph是图标小符号组件,便于使用精美的图标,如渲染多色图标。SymbolGlyph通过引用Resource资源来创建,资源引用类型可以通过$r创建Resource类型对象。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct SymbolGlyphPage{
  build() {
    Column(){
      Text() {
        SymbolSpan($r('sys.symbol.ohos_trash'))
          .fontWeight(FontWeight.Normal)
          .fontSize(96)
      }
      Row(){
        Text() {
          SymbolSpan($r('sys.symbol.arrow_down_circle_badge_vip_circle_filled'))
            .fontWeight(FontWeight.Normal)
            .fontSize(36)
        }
        Text() {
          SymbolSpan($r('sys.symbol.ohos_folder_badge_plus'))
            .fontWeight(FontWeight.Normal)
            .fontSize(72)
        }
        Text() {
          SymbolSpan($r('sys.symbol.play_arrow_triangle_2_circlepath'))
            .fontWeight(FontWeight.Normal)
            .fontSize(96)
        }
      }
      Row(){
        Text() {
          SymbolSpan($r('sys.symbol.heart_badge_plus'))
            .fontWeight(FontWeight.Lighter)
            .fontSize(96)
            .fontColor([Color.Red])
        }
        Text() {
          SymbolSpan($r('sys.symbol.ellipsis_message_1'))
            .fontWeight(FontWeight.Normal)
            .fontSize(96)
            .fontColor([Color.Yellow])
        }
        Text() {
          SymbolSpan($r('sys.symbol.ohos_wifi'))
            .fontWeight(FontWeight.Bold)
            .fontSize(96)
            .fontColor([Color.Blue])
        }
      }
    }
  }
}

5、文字样式代码示例

代码语言:javascript
代码运行次数:0
复制
import { LengthMetrics } from '@kit.ArkUI';
// 导入 LengthMetrics 模块,用于处理长度单位

@Entry
@Component
struct TextStylePage {
  // 定义一个居中对齐的段落样式对象
  alignCenterParagraphStyleAttr: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.Center });
  // 定义一个行高样式对象
  lineHeightStyle1: LineHeightStyle= new LineHeightStyle(LengthMetrics.vp(24));
  // 定义一个粗体文本样式对象
  boldTextStyle: TextStyle = new TextStyle({ fontWeight: FontWeight.Bold });

  // 创建一个可变样式字符串对象 paragraphStyledString1,包含多种样式
  paragraphStyledString1: MutableStyledString = new MutableStyledString("您的豪华钻石已过期1天\n续费可继续享受会员专属权益", [
    {
      // 应用 alignCenterParagraphStyleAttr 样式到字符串的前 4 个字符
      start: 0,
      length: 4,
      styledKey: StyledStringKey.PARAGRAPH_STYLE,
      styledValue: this.alignCenterParagraphStyleAttr
    },
    {
      // 应用自定义行高样式到字符串的前 4 个字符
      start: 0,
      length: 4,
      styledKey: StyledStringKey.LINE_HEIGHT,
      styledValue: new LineHeightStyle(LengthMetrics.vp(40))
    },
    {
      // 应用自定义字体样式到字符串的第 11 到第 24 个字符
      start: 11,
      length: 14,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontSize: LengthMetrics.vp(14), fontColor: Color.Grey })
    },
    {
      // 应用 alignCenterParagraphStyleAttr 样式到字符串的第 11 到第 14 个字符
      start: 11,
      length: 4,
      styledKey: StyledStringKey.PARAGRAPH_STYLE,
      styledValue: this.alignCenterParagraphStyleAttr
    },
    {
      // 应用 lineHeightStyle1 样式到字符串的第 11 到第 14 个字符
      start: 11,
      length: 4,
      styledKey: StyledStringKey.LINE_HEIGHT,
      styledValue: this.lineHeightStyle1
    }
  ]);

  // 创建一个可变样式字符串对象 paragraphStyledString2,包含多种样式
  paragraphStyledString2: MutableStyledString = new MutableStyledString("\n¥9.98¥15", [
    {
      // 应用 alignCenterParagraphStyleAttr 样式到整个字符串
      start: 0,
      length: 4,
      styledKey: StyledStringKey.PARAGRAPH_STYLE,
      styledValue: this.alignCenterParagraphStyleAttr
    },
    {
      // 应用自定义行高样式到整个字符串
      start: 0,
      length: 4,
      styledKey: StyledStringKey.LINE_HEIGHT,
      styledValue: new LineHeightStyle(LengthMetrics.vp(60))
    },
    {
      // 应用 boldTextStyle 样式到字符串的前 6 个字符
      start: 0,
      length: 6,
      styledKey: StyledStringKey.FONT,
      styledValue: this.boldTextStyle
    },
    {
      // 应用自定义字体样式到字符串的第 2 个字符
      start: 1,
      length: 1,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontSize: LengthMetrics.vp(18)})
    },
    {
      // 应用自定义字体样式到字符串的第 3 到第 6 个字符
      start: 2,
      length: 4,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontSize: LengthMetrics.vp(40)})
    },
    {
      // 应用自定义字体样式到字符串的第 7 到第 9 个字符
      start: 6,
      length: 3,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontColor: Color.Grey, fontSize: LengthMetrics.vp(14)})
    },
    {
      // 应用删除线样式到字符串的第 7 到第 9 个字符
      start: 6,
      length: 3,
      styledKey: StyledStringKey.DECORATION,
      styledValue: new DecorationStyle({ type: TextDecorationType.LineThrough, color: Color.Grey })
    }
  ]);

  // 创建一个可变样式字符串对象 paragraphStyledString3,包含多种样式
  paragraphStyledString3: MutableStyledString = new MutableStyledString("\n02时06分后将失去该优惠", [
    {
      // 应用 alignCenterParagraphStyleAttr 样式到整个字符串
      start: 0,
      length: 4,
      styledKey: StyledStringKey.PARAGRAPH_STYLE,
      styledValue: this.alignCenterParagraphStyleAttr
    },
    {
      // 应用自定义行高样式到整个字符串
      start: 0,
      length: 4,
      styledKey: StyledStringKey.LINE_HEIGHT,
      styledValue: new LineHeightStyle(LengthMetrics.vp(30))
    },
    {
      // 应用自定义字体样式到字符串的第 2 和第 5 个字符
      start: 1,
      length: 2,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontColor: '#FFD700', fontWeight: FontWeight.Bold })
    },
    {
      // 应用自定义字体样式到字符串的第 5 和第 6 个字符
      start: 4,
      length: 2,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontColor: '#FFD700', fontWeight: FontWeight.Bold })
    }
  ]);

  // 创建一个文本控制器对象
  controller: TextController = new TextController();

  build() {
    // 构建页面布局
    Row() {
      Column( { space : 5 }) {
        // 显示文本内容,使用 controller 控制样式
        Text(undefined, { controller: this.controller })
          .width(240)
          .copyOption(CopyOptions.InApp)
          .draggable(true)
          .onAppear(()=>{
            // 在页面显示时,将 paragraphStyledString3 追加到 paragraphStyledString2 后面
            this.paragraphStyledString2.appendStyledString(this.paragraphStyledString3)
            // 将 paragraphStyledString2 追加到 paragraphStyledString1 后面
            this.paragraphStyledString1.appendStyledString(this.paragraphStyledString2)
            // 设置 controller 的样式字符串为 paragraphStyledString1
            this.controller.setStyledString(this.paragraphStyledString1)
          })

        // 显示一个按钮,用于立即续费
        Button("限时9.98元 立即续费")
          .width(200)
          .fontColor(Color.White)
          .fontSize(18)
          .backgroundColor('#3CB371')
          .margin({ bottom: 10 })
      }
      // 为 Column 组件添加边框
      .borderWidth(1).borderColor('#FFDEAD')
      // 为 Column 组件添加左边距
      .margin({ left: 10 })
    }
    // 设置 Row 组件的高度为页面的 60%
    .height('60%')
  }
}

6、弹窗

模态弹窗

模态(Modal)是UI组件或视图的一种状态。其在消失之前,用户只能对处于模态的组件或视图进行响应,不能操作其他非模态的组件或视图,干扰性比较强。

名称

使用场景

AlertDialog

通常用来展示用户当前需要或必须关注的信息或操作。如用户操作一个敏感行为时响应一个二次确认的弹窗。

ActionSheet

当需要用户关注或确认的信息存在列表选择时使用。

CustomDialog

当用户需要自定义弹窗内的组件和内容时使用。

Popup

用于为指定的组件做信息提示。如点击一个问号图标弹出一段气泡提示。

Menu/ContextMenu

用于给指定的组件绑定用户可执行的操作,如长按图标展示操作选项等。

通用弹窗与气泡弹窗示例
代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct AlertPage {
  @State handlePopup: boolean = false;

  build() {
    Column({ space: 5 }) {
      Button('模态按钮')
        .onClick(() => {
          AlertDialog.show(
            {
              title: '弹窗标题',
              subtitle: '副标题',
              message: '消息文本',
              autoCancel: true,
              alignment: DialogAlignment.Bottom,
              gridCount: 4,
              offset: { dx: 0, dy: -20 },
              primaryButton: {
                value: '取消',
                action: () => {
                  console.info('点击了取消')
                }
              },
              secondaryButton: {
                enabled: true,
                defaultFocus: true,
                style: DialogButtonStyle.HIGHLIGHT,
                value: '确定',
                action: () => {
                  console.info('点击了确定')
                }
              }
            }
          )
        }).backgroundColor(0x317aff)

      Button('气泡按钮')
        .onClick(() => {
          this.handlePopup = !this.handlePopup
        })
        .bindPopup(this.handlePopup, {
          message: '这是气泡按钮的显示内容',
          placementOnTop: true,
          showInSubWindow: false,
          primaryButton: {
            value: '确认',
            action: () => {
              this.handlePopup = !this.handlePopup
              console.info('点击确认操作')
            }
          },
          // 第二个按钮
          secondaryButton: {
            value: '取消',
            action: () => {
              this.handlePopup = !this.handlePopup
              console.info('点击取消操作')
            }
          },
          onStateChange: (e) => {
            console.info(JSON.stringify(e.isVisible))
            if (!e.isVisible) {
              this.handlePopup = false
            }
          }
        })
        .position({ x: 100, y: 150 })
    }.width('100%').margin({ top: 50 })
  }
}

7、按钮

Button有三种可选类型,分别为胶囊类型(Capsule)、圆形按钮(Circle)和普通按钮(Normal),通过type进行设置。

代码语言:javascript
代码运行次数:0
复制
@Entry
@Component
struct ButtonPage {
  build() {
    Column() {
      Row() {
        // 胶囊按钮(默认类型)
        Button('默认', { type: ButtonType.Capsule, stateEffect: false })
          .backgroundColor(0x317aff)
          .width(90)
          .height(40)
        // 圆形按钮
        Button('圆的', { type: ButtonType.Circle, stateEffect: false })
          .backgroundColor(0x317aff)
          .width(90)
          .height(90)
        // 普通按钮
        Button('确认', { type: ButtonType.Normal, stateEffect: true })
          .borderRadius(8)
          .backgroundColor(0x317aff)
          .width(90)
          .height(40)
      }.width('100%').height('5%').margin({ top: 100 })

      Row() {
        // 设置边框弧度。
        Button('弧度边框', { type: ButtonType.Normal })
          .borderRadius(20)
          .height(40)
        // 设置文本样式。
        Button('字体样式', { type: ButtonType.Normal })
          .fontSize(20)
          .fontColor(Color.Pink)
          .fontWeight(800)
        // 设置背景颜色。
        Button('背景颜色').backgroundColor(0xF55A42)
      }.width('100%').height('5%').margin({ top: 100 })

      Row() {
        // 图片按钮
        Button({ type: ButtonType.Circle, stateEffect: true }) {
          Image($r('app.media.random_1_1024x1024')).width(30).height(30)
        }.width(55).height(55).backgroundColor(0xF55A42)

      }.width('100%').height('5%').margin({ top: 100 })
    }
  }
}

8、加载网络数据函数

代码语言:javascript
代码运行次数:0
复制
import http from '@ohos.net.http';
import { JSON } from '@kit.ArkTS';

@Entry
@Component
struct AjaxAPIPage{
  @State str_info:string ="";
  requestData() {
    let httpRequest = http.createHttp();
    // 设置请求的URL,这里替换为真实有效的接口地址
    let url = "http://39.107.126.100:5000/getInfo";
    httpRequest.request(
      url,
      {
        method: http.RequestMethod.GET
      },
      (err, data) => {
        if (!err) {
          // 请求成功,处理返回的数据,假设返回的数据是JSON格式
          let responseData = data.result.toString();
          console.log("原始返回数据: " + responseData);
          // 解析JSON数据
          try {
            console.log(responseData);
            // 在这里可以进一步对解析后的jsonObj进行操作,比如获取特定属性的值等
            this.str_info = responseData;
          } catch (e) {
            console.error("JSON解析出错: " + e);
          }
        } else {
          console.error("请求出错: " + err);
        }
        // 请求结束后关闭请求实例
        httpRequest.destroy();
      }
    );
  }
  build() {
    Column(){
      Button("加载数据").onClick(()=>{
        this.requestData()
        let info = JSON.parse(this.str_info)
      })
      Text(this.str_info).fontSize(20)
    }
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-02-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 第四章 基础控件
    • 1、创建文本(Text)
      • 添加子组件
      • 文本样式
      • 大小写转换
      • 文字事件添加
      • 自定义文本样式
      • 新闻示例
    • 2、文本输入(TextInput/TextArea)
      • 创建输入框
      • 设置输入框类型
      • 添加事件
      • 登录窗体示例
      • 键盘避让
    • 3、富文本(RichEditor)
      • 添加文本与获取信息
    • 4、图标小符号 (SymbolGlyph/SymbolSpan)
    • 5、文字样式代码示例
    • 6、弹窗
      • 模态弹窗
      • 通用弹窗与气泡弹窗示例
    • 7、按钮
    • 8、加载网络数据函数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档