• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Resource Categories and Access
2
3During application development, you may need to use different resources, such as colors, fonts, spacing, and images, based on the device or configuration. Depending on the resource type, you can achieve this using the following methods:
4
5- Application resources: Configure device- or configuration-specific resources in the resource files.
6
7- System resources: Use the preset resource definitions.
8
9## Resource Categories
10
11Resource files used during application development must be stored in specified directories for management. The **resources** directory consists of three types of subdirectories: the **base** subdirectory, qualifiers subdirectories, and the **rawfile** subdirectory. The common resource files used across projects in the stage model are stored in the **resources** directory under **AppScope**.
12
13The **base** subdirectory is provided by default, and the qualifiers subdirectories are created on your own. When your application needs to use a resource, the system preferentially searches the qualifiers subdirectories that match the current device state. The system searches the **base** subdirectory for the target resource only when the **resources** directory does not contain any qualifiers subdirectories that match the current device state or the target resource is not found in the qualifiers subdirectories. The **rawfile** directory is not searched for resources.
14
15Example of the **resources** directory:
16
17```
18resources
19|---base
20|   |---element
21|   |   |---string.json
22|   |---media
23|   |   |---icon.png
24|   |---profile
25|   |   |---test_profile.json
26|---en_US  // Default directory. When the device language is en-us, resources in this directory are preferentially matched.
27|   |---element
28|   |   |---string.json
29|   |---media
30|   |   |---icon.png
31|   |---profile
32|   |   |---test_profile.json
33|---zh_CN  // Default directory. When the device language is zh-cn, resources in this directory are preferentially matched.
34|   |---element
35|   |   |---string.json
36|   |---media
37|   |   |---icon.png
38|   |---profile
39|   |   |---test_profile.json
40|---en_GB-vertical-car-mdpi // Example of a qualifiers subdirectory, which needs to be created on your own.
41|   |---element
42|   |   |---string.json
43|   |---media
44|   |   |---icon.png
45|   |---profile
46|   |   |---test_profile.json
47|---rawfile // Other types of files are saved as raw files and will not be integrated into the resources.index file. You can customize the file name as needed.
48```
49
50**Table 1** Classification of the resources directory
51
52| Category   | base Subdirectory                          | Qualifiers Subdirectory                                   | rawfile Subdirectory                                |
53| ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
54| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.<br>Resource group subdirectories are located at the second-level subdirectories in the **base** directory to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectory](#resource-group-subdirectory).| **en_US** and **zh_CN** are two default qualifiers subdirectories. You need to create other qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectory](#qualifiers-subdirectory).<br>Resource group subdirectories are located at the second level of qualifiers subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectory](#resource-group-subdirectory).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.<br>However, resource files in the **rawfile** subdirectory will not be matched based on the device status.|
55| Compilation| Resource files in the subdirectories are compiled into binary files, and each resource file is assigned an ID.           | Resource files in the subdirectories are compiled into binary files, and each resource file is assigned an ID.           | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files.   |
56| Reference| Resource files in the subdirectory are referenced based on the resource type and resource name.           | Resource files in the subdirectory are referenced based on the resource type and resource name.           | Resource files in the subdirectory are referenced based on the file path and file name.                         |
57
58
59### Qualifiers Subdirectory
60
61The name of a qualifiers subdirectory consists of one or more qualifiers that represent the application scenarios or device characteristics, covering the mobile country code (MCC), mobile network code (MNC), language, script, country or region, screen orientation, device type, night mode, and screen density. The qualifiers are separated using underscores (\_) or hyphens (\-). When creating a qualifiers subdirectory, you need to understand the directory naming conventions and the rules for matching qualifiers subdirectories and the device status.
62
63**Naming Conventions for Qualifiers Subdirectories**
64
65- Qualifiers are ordered in the following sequence: **\_MCC_MNC-language_script_country/region-orientation-device-color mode-density**. You can select one or multiple qualifiers to name your subdirectory based on your application scenarios and device characteristics.
66
67- Separation between qualifiers: The language, script, and country/region qualifiers are separated using underscores (\_); the MNC and MCC qualifiers are also separated using underscores (\_); other qualifiers are separated using hyphens (-). For example, **zh_Hant_CN** and **zh_CN-car-ldpi**.
68
69- Value range of qualifiers: The value of each qualifier must meet the requirements specified in the following table. Otherwise, the resource files in the resources directory cannot be matched.
70
71**Table 2** Requirements for qualifier values
72
73| Qualifier Type      | Description and Value Range                                 |
74| ----------- | ---------------------------------------- |
75| MCC&MNC| Mobile country code and mobile network code, which are obtained from the network where the device is registered. The MCC can be either followed by the MNC with an underscore (\_) in between or be used independently. For example, **mcc460** indicates China, and **mcc460\_mnc00** indicates China\_China Mobile.<br>For details about the value range, refer to **ITU-T E.212** (the international identification plan for public networks and subscriptions).|
76| Language         | Language used by the device. The value consists of two or three lowercase letters. for example, **zh** indicates Chinese, en indicates English, and **mai** indicates Maithili.<br>For details about the value range, refer to **ISO 639** (codes for the representation of names of languages).|
77| Script         | Script type used by the device. The value starts with one uppercase letter followed by three lowercase letters. For example, **Hans** indicates simplified Chinese, and **Hant** indicates traditional Chinese.<br>For details about the value range, refer to **ISO 15924** (codes for the representation of names of scripts).||
78| Country/Region      | Country or region where the user is located. The value consists of two or three uppercase letters or three digits. For example, **CN** indicates China, and **GB** indicates the United Kingdom.<br>For details about the value range, refer to **ISO 3166-1** (codes for the representation of names of countries and their subdivisions).||
79| Screen orientation        | Screen orientation of the device. The value can be:<br>- **vertical**: portrait orientation<br>- **horizontal**: landscape orientation|
80| Type of the registered device.       | Device type. The value can be:<br>- **car**: head unit<br>- **tv**: smart TV<br>- **wearable**: smart wearable|
81| Color mode       | Color mode of the device. The value can be:<br>- **dark**: dark mode<br>- **light**: light mode|
82| Screen density       | Screen density of the device, in dpi. The value can be:<br>- **sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].<br>- **mdpi**: screen density with medium-scale dots per inch (MDPI). This value is applicable for devices with a DPI range of (120, 160].<br>- **ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].<br>- **xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].<br>- **xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].<br>- **xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640].|
83
84**Rules for Matching Qualifiers subdirectories and Device Resources**
85
86- Qualifiers are matched with the device resources in the following priorities: MCC&MNC &gt; locale (options: language, language\_script, language\_country/region, and language\_script\_country/region) &gt; screen orientation &gt; device type &gt; color mode &gt; screen density.
87
88- If the qualifiers subdirectories contain the **MCC, MNC, language, script, screen orientation, device type, and color mode** qualifiers, their values must be consistent with the current device status so that the subdirectories can be used for matching the device resources. For example, the qualifiers subdirectory **zh\_CN-car-ldpi** cannot be used for matching the resource files labeled **en\_US**.
89
90
91### Resource Group Subdirectory
92
93You can create resource group subdirectories (including element, media, and profile) in the **base** and qualifiers subdirectories to store resource files of specific types.
94
95
96  **Table 3** Resource group subdirectories
97
98| Resource Group Subdirectory  | Description                                    | Resource File                                    |
99| ------- | ---------------------------------------- | ---------------------------------------- |
100| element | Element resources. Each type of data is represented by a JSON file. (Only files are supported in this directory.) The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integers<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:<br>-&nbsp;boolean.json<br>-&nbsp;color.json<br>-&nbsp;float.json<br>-&nbsp;intarray.json<br>-&nbsp;integer.json<br>-&nbsp;pattern.json<br>-&nbsp;plural.json<br>-&nbsp;strarray.json<br>-&nbsp;string.json |
101| media   | Media resources, including non-text files such as images, audios, and videos. (Only files are supported in this directory.)              | The file name can be customized, for example, **icon.png**.                    |
102| profile  | Custom configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. (Only files are supported in this directory.)       | The file name can be customized, for example, **test_profile.json**.          |
103
104**Media Resource Types**
105
106**Table 4** Image resource types
107
108| Format  | File Name Extension|
109| ---- | ----- |
110| JPEG | .jpg  |
111| PNG  | .png  |
112| GIF  | .gif  |
113| SVG  | .svg  |
114| WEBP | .webp |
115| BMP  | .bmp  |
116
117**Table 5** Audio and video resource types
118
119| Format                                  | File Name Extension        |
120| ------------------------------------ | --------------- |
121| H.263                                | .3gp <br>.mp4   |
122| H.264 AVC <br> Baseline Profile (BP) | .3gp <br>.mp4   |
123| MPEG-4 SP                            | .3gp            |
124| VP8                                  | .webm <br> .mkv |
125
126**Resource File Examples**
127
128The content of the **color.json** file is as follows:
129
130
131```json
132{
133    "color": [
134        {
135            "name": "color_hello",
136            "value": "#ffff0000"
137        },
138        {
139            "name": "color_world",
140            "value": "#ff0000ff"
141        }
142    ]
143}
144```
145
146The content of the **float.json** file is as follows:
147
148
149```json
150{
151    "float":[
152        {
153            "name":"font_hello",
154            "value":"28.0fp"
155        },
156	{
157            "name":"font_world",
158            "value":"20.0fp"
159        }
160    ]
161}
162```
163
164The content of the **string.json** file is as follows:
165
166
167```json
168{
169    "string":[
170        {
171            "name":"string_hello",
172            "value":"Hello"
173        },
174	{
175            "name":"string_world",
176            "value":"World"
177        },
178	{
179            "name":"message_arrive",
180            "value":"We will arrive at %s."
181        }
182    ]
183}
184```
185
186The content of the **plural.json** file is as follows:
187
188
189```json
190{
191    "plural":[
192        {
193            "name":"eat_apple",
194            "value":[
195                {
196                    "quantity":"one",
197                    "value":"%d apple"
198                },
199                {
200                    "quantity":"other",
201                    "value":"%d apples"
202                }
203            ]
204        }
205    ]
206}
207```
208
209## Resource Access
210
211### Application Resources
212
213**Creating a Resource File**
214
215You can create a subdirectory and its files under the **resources** directory based on the above descriptions of the qualifiers subdirectories and resource group subdirectories.
216
217DevEco Studio provides a wizard for you to create resource directories and resource files.
218
219- Creating a resource directory and resource file
220
221  Right-click the **resources** directory and choose **New > Resource File**. This operation creates a subdirectory and a resource file simultaneously.	If no qualifier is selected, the file is created in a resource type subdirectory under **base**. If one or more qualifiers are selected, the system automatically generates a subdirectory and creates the file in this subdirectory. To select a qualifier, highlight it under **Available qualifiers** and click the right arrow. To deselect a qualifier, highlight it under **Selected qualifiers** and click the left arrow. In **File name**, enter the name of the resource file to create. In **Resource type**, select the type of the resource group, which is **element** by default. In **Root Element**, select a resource type. The created subdirectory is automatically named in the format of *Qualifiers.Resource group type*. For example, if you create a subdirectory by setting **Color Mode** to **Dark** and **Resource type** to **Element**, the system automatically generates a subdirectory named **dark.element**.
222
223  ![create-resource-file-1](figures/create-resource-file-1.png)
224
225- Creating a resource directory
226
227  Right-click the **resources** directory and choose **New > Resource Directory**. This operation creates a subdirectory only. By default, the **base** subdirectory is created. You can create qualifiers subdirectories as required, by specifying the qualifier and resource group type. After determining the qualifier, select a resource group type. Currently, the resource group type can be **Element**, **Media**, or **Profile**. After a resource group is created, a directory name is automatically generated.
228
229  ![create-resource-file-2](figures/create-resource-file-2.png)
230
231- Creating a resource file
232
233  Right-click a subdirectory under **resources** and choose **New > *example* Resource File**. This operation creates a resource file under this subdirectory. For example, you can create an element resource file in the **element** subdirectory.
234
235  ![create-resource-file-3](figures/create-resource-file-3.png)
236
237**Accessing Application Resources**
238
239To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource.
240
241When referencing resources in the **rawfile** subdirectory, use the `"$rawfile('filename')"` format. Wherein **filename** indicates the relative path of a file in the **rawfile** subdirectory, which must contain the file name extension and cannot start with a slash (/).
242
243> **NOTE**
244>
245> Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined.
246>
247> The return value of `$r` is a Resource object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) method.
248
249In the ***example*.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Subdirectory](#resource-group-subdirectory):
250
251```ts
252Text($r('app.string.string_hello'))
253  .fontColor($r('app.color.color_hello'))
254  .fontSize($r('app.float.font_hello'))
255
256Text($r('app.string.string_world'))
257  .fontColor($r('app.color.color_world'))
258  .fontSize($r('app.float.font_world'))
259
260// Reference string resources. The second parameter of $r is used to replace %s, and value is "We will arrive at five of the clock".
261Text($r('app.string.message_arrive', "five of the clock"))
262  .fontColor($r('app.color.color_hello'))
263  .fontSize($r('app.float.font_hello'))
264
265// Reference plural resources. The first parameter indicates the plural resource, the second parameter indicates the number of plural resources, and the third parameter indicates the substitute of %d.
266// The value is "5 apple" in singular form and "5 apples" in plural form.
267Text($r('app.plural.eat_apple', 5, 5))
268  .fontColor($r('app.color.color_world'))
269  .fontSize($r('app.float.font_world'))
270
271Image($r('app.media.my_background_image'))  // Reference media resources.
272
273Image($rawfile('test.png'))                 // Reference an image in the rawfile directory.
274
275Image($rawfile('newDir/newTest.png'))       // Reference an image in the rawfile directory.
276```
277
278### System Resources
279
280System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style.
281
282To reference a system resource, use the `"$r('sys.type.resource_id')"` format. Wherein: **sys** indicates a system resource; **type** indicates the resource type, which can be **color**, **float**, **string**, or **media**; **resource_id** indicates the resource ID.
283
284> **NOTE**
285>
286> - Use of system resources is supported in the declarative development paradigm, but not in the web-like development paradigm.
287>
288> - For details about the implementation of preconfigured resources, visit the [OpenHarmony/resources repository](https://gitee.com/openharmony/resources/tree/master/systemres/main/resources). The directory structure there is similar to that of the **resources** directory in the project. Resource qualifiers are used to match resources with different devices and device status.
289
290```ts
291Text('Hello')
292  .fontColor($r('sys.color.ohos_id_color_emphasize'))
293  .fontSize($r('sys.float.ohos_id_text_size_headline1'))
294  .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
295  .backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
296
297Image($r('sys.media.ohos_app_icon'))
298  .border({
299    color: $r('sys.color.ohos_id_color_palette_aux1'),
300    radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2
301  })
302  .margin({
303    top: $r('sys.float.ohos_id_elements_margin_horizontal_m'),
304    bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')
305  })
306  .height(200)
307  .width(300)
308```
309