
2.3.2 Text和TextField
文本框通过Text组件来实现,用来显示文本字符信息,是HarmonyOS中最常用的一个组件。编辑框通过TextField组件来实现,它继承自Text类,与Text组件的属性和用法一样,只不过它允许改变其中的内容,所以这里把Text组件和 TextField 组件放到一起来讲解。Text 组件的属性较多,开发者可以通过设置这些属性来改变文本内容、字号、颜色、样式等。下面介绍Te x t组件的具体用法。
Text组件和 TextField组件除了有 Component的通用属性,还有一些自有属性,常用的自有属性见表2-6。
表2-6 Text组件与TextField组件的自有属性

续表

Te x t组件的自有属性非常多,表2-6只列出了一些常用的属性,下面创建一个Te x t组件。
1.指定具体尺寸的Text组件


页面预览效果如图2-31所示。
这里为 Te x t 组件添加了背景颜色以方便观察,在其中写入了一行文本信息:“1.hello world!”,字号设置为12vp,并且设置了底部外边距bottom_margin为12vp。
2.指定文本位置

页面的预览效果如图2-32所示。

图2-31 指定具体尺寸的Text组件

图2-32 指定文本位置的Text组件
3.一段超长文本的显示


页面的预览效果如图2-33所示,由于文本太长,超过屏幕的部分无法显示。
4.超长文本的多行显示

页面的预览效果如图 2-34 所示,Text 组件通过设置 ohos:multiple_lines="true",可以将超出部分的文本另起一行显示。

图2-33 超长文本的显示

图2-34 超长文本的多行显示
5.超长文本的单行省略显示


页面的预览效果如图2-35所示。
6.改变字体样式

页面的预览效果如图2-36所示。

图2-35 超长文本的单行省略显示

图2-36 改变字体样式
Te x t组件的属性非常多,由于篇幅有限,只能列举这些常用的属性。在上面的案例中,涉及文本框大小、字号、文本位置和长文本处理。在实际应用中,为了避免出现文本长度超过Text组件宽度而导致信息被截断的情况,在对Text组件进行处理时都要考虑这些情况,可以多行显示,那么需要限制最大行数,也可以单行显示,则需要考虑在末尾处用省略号给出提示,以免文本显示不全。当然,具体的处理方式要根据业务特点来决定。
输入框的特点是,如果点击输入框,就会弹出输入法框,可以对其中的文本信息进行修改。
下面来介绍 TextField 组件。TextField 组件与 Text 组件的区别就在于TextField 组件中的文本信息是可编辑的。与 Text 组件相比,TextField 组件的自有属性如表2-7所示。
表2-7 TextField组件的自有属性

下面来看这个属性的效果。


图2-37 basement属性演示
上面两种输入框的页面预览效果如图 2-37 所示,可以看到basement其实是输入框下方的一条线,这条线可以标识输入框的尺寸范围,以带来良好的用户体验。