5,143
社区成员
发帖
与我相关
我的任务
分享
当开发应用的时候,我们会对一些布局的风格有统一的设计。例如多Text组件组成的表单界面,我们会将字体的大小、颜色等等外观设置一致,其中有大量的重复XML代码。而修改其中一个共同属性的时候(例如字体大小)又需要逐一的去修改每个Text组件。这个时候pattern就排上用场了,先看实例。
例如我们要完成下面的界面:
下面的是在使用pattern之前的布局,其中大量的重复字段,维护起来也很复杂
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:orientation="vertical"
ohos:total_weight="8"
ohos:width="match_parent">
<Text
ohos:background_element="$graphic:bg_example_pattern"
ohos:height="0"
ohos:margin="18vp"
ohos:text="条目一"
ohos:text_alignment="center"
ohos:text_color="#FFFFFF"
ohos:text_size="32fp"
ohos:weight="1"
ohos:width="match_parent"/>
<Text
ohos:background_element="$graphic:bg_example_pattern"
ohos:height="0"
ohos:margin="18vp"
ohos:text="条目二"
ohos:text_alignment="center"
ohos:text_color="#FFFFFF"
ohos:text_size="32fp"
ohos:weight="1"
ohos:width="match_parent"/>
<Text
ohos:background_element="$graphic:bg_example_pattern"
ohos:height="0"
ohos:margin="18vp"
ohos:text="条目三"
ohos:text_alignment="center"
ohos:text_color="#FFFFFF"
ohos:text_size="32fp"
ohos:weight="1"
ohos:width="match_parent"/>
<Text
ohos:background_element="$graphic:bg_example_pattern"
ohos:height="0"
ohos:margin="18vp"
ohos:text="条目四"
ohos:text_alignment="center"
ohos:text_color="#FFFFFF"
ohos:text_size="32fp"
ohos:weight="1"
ohos:width="match_parent"/>
<Text
ohos:background_element="$graphic:bg_example_pattern"
ohos:height="0"
ohos:margin="18vp"
ohos:text="条目五"
ohos:text_alignment="center"
ohos:text_color="#FFFFFF"
ohos:text_size="32fp"
ohos:weight="1"
ohos:width="match_parent"/>
</DirectionalLayout>
下面是使用pattern后的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:orientation="vertical"
ohos:total_weight="8"
ohos:width="match_parent">
<Text
ohos:height="0"
ohos:text="条目一"
ohos:text_alignment="center"
ohos:theme="$pattern:pattern_example"
ohos:width="match_parent"/>
<Text
ohos:height="0"
ohos:text="条目二"
ohos:text_alignment="center"
ohos:theme="$pattern:pattern_example"
ohos:width="match_parent"/>
<Text
ohos:height="0"
ohos:text="条目三"
ohos:text_alignment="center"
ohos:theme="$pattern:pattern_example"
ohos:width="match_parent"/>
<Text
ohos:height="0"
ohos:text="条目四"
ohos:text_alignment="center"
ohos:theme="$pattern:pattern_example"
ohos:width="match_parent"/>
<Text
ohos:height="0"
ohos:text="条目五"
ohos:text_alignment="center"
ohos:theme="$pattern:pattern_example"
ohos:width="match_parent"/>
</DirectionalLayout>
pattern.json 部分代码
{
"pattern": [
{
"name": "pattern_example",
"value": [
{
"name": "background_element",
"value": "$graphic:bg_example_pattern"
},
{
"name": "margin",
"value": "18vp"
},
{
"name": "text_color",
"value": "#FFFFFF"
},
{
"name": "text_size",
"value": "32fp"
},
{
"name": "weight",
"value": "1"
}
]
}
]
}
使用pattern后我们只需要在pattern中修改对应的属性就会全部应用到引用该配置的组件。对于后期的维护也大大的提升了效率,不再需要逐一修改(而且可能存在漏改的组件)。
收藏