鸿蒙系列--组件介绍之资源引用类型

Resource

资源引用类型用于设置组件属性的值。

        可以将资源文件(字符串、颜色、大小、图片、音频、视频等)统一存放于resources目录下,便于统一维护。

        系统可以根据当前配置加载合适的资源,例如,可以根据屏幕尺寸呈现不同的布局效果,或根据语言设置提供不同的字符串等。

举例:

@Entry
@Component
struct ButtonPage {

  build() {
    Row() {
      Column() {
        Button('登录', { type: ButtonType.Capsule, stateEffect: true })
          .width(300)
          .height(40)
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .backgroundColor('#007DFF')
      }
      .width('100%')
    }
    .height('100%')
  }
}

上面这个测试代码中直接在代码中写入了字符串和数字这样的硬编码,导致不好维护,将这些硬编码相关的属性定义到资源文件中:entry/src/main/resources

1.在string.json中定义要显示的文本

{
  "string": [
    {
      "name": "login_text",
      "value": "登录"
    }
  ]
} 

2.在float.json中定义Button的宽高和字体大小

{
  "float": [
    {
      "name": "button_width",
      "value": "300vp"
    },
    {
      "name": "button_height",
      "value": "40vp"
    },
    {
      "name": "login_fontSize",
      "value": "16fp"
    }
  ]
}

3.在color.json中定义Button的背景颜色

{
  "color": [
    {
      "name": "button_color",
      "value": "#007DFF"
    }
  ]
}

4.通过“$r('app.type.name')”的形式引用应用资源

  • app:代表应用内resources目录中定义的资源;
  • type:代表资源类型(或资源的存放位置)可以取“color”、“float”、“string”、“plural”、“media”;
  • name:代表资源命名,自定义
@Entry
@Component
struct ButtonPage {

  build() {
    Row() {
      Column() {
        Button($r('app.string.login_text'), { type: ButtonType.Capsule, stateEffect: true })
          .width($r('app.float.button_width'))
          .height($r('app.float.button_height'))
          .fontSize($r('app.float.login_fontSize'))
          .fontWeight(FontWeight.Medium)
          .backgroundColor($r('app.color.button_color'))
      }
      .width('100%')
    }
    .height('100%')
  }
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-22 07:56:10       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-22 07:56:10       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-22 07:56:10       82 阅读
  4. Python语言-面向对象

    2023-12-22 07:56:10       91 阅读

热门阅读

  1. 流媒体知识总结

    2023-12-22 07:56:10       62 阅读
  2. 在 Go 语言中使用 regexp 包处理正则表达式

    2023-12-22 07:56:10       48 阅读
  3. Ansible3

    Ansible3

    2023-12-22 07:56:10      60 阅读
  4. css学习笔记5

    2023-12-22 07:56:10       62 阅读
  5. Android 9.0 应用权限屏蔽位置信息

    2023-12-22 07:56:10       43 阅读
  6. MongoDB的面试题与答案

    2023-12-22 07:56:10       56 阅读
  7. GBASE南大通用集群负载均衡

    2023-12-22 07:56:10       54 阅读
  8. hive中map相关函数总结

    2023-12-22 07:56:10       72 阅读
  9. unity中Android各版本对应的SDK版本

    2023-12-22 07:56:10       60 阅读