文本(Text)是用来显示字符串的组件,在界面上显示为一块文本区域。Text 作为一个基本组件,有很多扩展,常见的有按钮组件 Button,文本编辑组件 TextField。
使用 Text
- 创建 Text
<Text
ohos:id="$+id:text"
ohos:width="match_content"
ohos:height="match_content"
ohos:text="Text"
ohos:background_element="$graphic:color_gray_element"/>
color_gray_element.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<solid
ohos:color="#ff888888"/>
</shape>
图1 创建一个 Text
- 设置背景
常用的背景如常见的文本背景、按钮背景,可以采用XML格式放置在 graphic 目录下。
在“Project”窗口,打开“entry > src > main > resources > base”,右键点击“base”文件夹,选择“New > Directory”,命名为“graphic”。右键点击“graphic”文件夹,选择“New > File”,命名为“textelement.xml”。
图2 创建 textelement.xml 文件后的 resources 目录结构
在 textelement.xml 中定义文本的背景:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<corners
ohos:radius="20"/>
<solid
ohos:color="#ff888888"/>
</shape>
在 first_layout.xml 中引用上面定义的文本背景:
<Text
ohos:id="$+id:text"
ohos:width="match_content"
ohos:height="match_content"
ohos:text="Text"
ohos:background_element="$graphic:textelement"/>
- 设置字体大小和颜色
<Text
ohos:id="$+id:tex