resources目录
具体说明如下表。
本文主要讲解这些资源如何使用。
资源引用
color.json
color.json用于存储颜色。
- color.json
{
"color": [
{
"name": "color_text",
"value": "#ff0000"
}
]
}
- xml
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text_color="$color:color_text"/>
- java
Text text = findComponentById(ResourceTable.Id_text);
try {
// 设置字体颜色
int color = getResourceManager().getElement(ResourceTable.Color_color_text).getColor();
text.setTextColor(new Color(color));
} catch (IOException e) {
e.printStackTrace();
} catch (NotExistException e) {
e.printStackTrace();
} catch (WrongTypeException e) {
e.printStackTrace();
}
string.json
string.json用于存储字符串。鸿蒙应用开发中,需要同时配置中英文。
- element/string.json
{
"string": [
{
"name": "resource_reference",
"value": "resource_reference"
}
]
}
- en.element/string.json
{
"string": [
{
"name": "resource_reference",
"value": "resource_reference"
}
]
}
- zh.element/string.json
{
"string": [
{
"name": "resource_reference",
"value": "资源引用"
}
]
}
- xml
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="$string:resource_reference"/>
- java
text.setText(ResourceTable.String_resource_reference);
boolean.json
boolean.json用于存储布尔值。
- boolean.json
{
"boolean": [
{
"name": "isPhone",
"value": true
}
]
}
- xml
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:enabled="$boolean:isPhone"/>
- java
// 布尔
boolean isPhone = getResourceManager().getElement(ResourceTable.Boolean_isPhone).getBoolean();
text.setVisibility(isPhone ? Component.VISIBLE : Component.INVISIBLE);
float.json
float.json用于存储浮点型数据。
- float.json
{
"float": [
{
"name": "rotation",
"value": "90.0"
}
]
}
- xml
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:rotate="$float:rotation"/>
- java
// 浮点,旋转文本
float width = getResourceManager().getElement(ResourceTable.Float_rotation).getFloat();
text.setRotation(width);
graphic
该文件下的xml文件通常用于设置组件背景。
- bg_text.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<!-- 颜色-->
<solid ohos:color="$color:color_text"/>
<!-- 圆角-->
<corners ohos:radius="$float:radius"/>
</shape>
- xml引用
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:bg_text"/>
- java
// 设置背景
ShapeElement background = new ShapeElement(this, ResourceTable.Graphic_bg_text);
text.setBackground(background);
media
表示媒体资源,包括图片、音频、视频等非文本格式的文件。
- xml
<Image
ohos:height="match_content"
ohos:width="match_content"
ohos:image_src="$media:icon"/>
- java
image.setPixelMap(ResourceTable.Id_image);
rawfile
引用指定文件路径。
- rawfile/test.txt
// 指定文件引用
RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry("entry/resources/rawfile/test.text");