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%')
}
}