自学鸿蒙应用开发(6)- TextField组件
本文介绍在鸿蒙应用中TextField组件的基本用法。
增加TextField组件
如下代码中25行~32行所示,在布局中增加TextField组件。
<DirectionalLayoutxmlns:ohos="http://schemas.huawei.com/res/ohos"ohos:height="match_parent"ohos:width="match_parent"ohos:orientation="vertical"><Componentohos:height="0vp"ohos:weight="3"ohos:width="match_parent"/><DirectionalLayoutxmlns:ohos="http://schemas.huawei.com/res/ohos"ohos:height="match_content"ohos:width="match_content"ohos:layout_alignment="center"ohos:orientation="vertical"><Imageohos:id="$+id:image"ohos:width="match_content"ohos:height="match_content"ohos:layout_alignment="center"ohos:image_src="$media:DevEco"/><TextFieldohos:id="$+id:text_field"ohos:width="match_parent"ohos:height="30vp"ohos:text_size="20fp"ohos:hint="Please input text and press [Click me!] button."ohos:background_element="$graphic:background_text_field"/><Buttonohos:id="$+id:hello_button"ohos:width="match_content"ohos:height="match_content"ohos:text_size="27fp"ohos:text="Click me!"ohos:layout_alignment="center"ohos:background_element="$graphic:background_button"ohos:margin="15vp"ohos:right_padding="8vp"ohos:left_padding="8vp"/>DirectionalLayout><Componentohos:height="0vp"ohos:weight="5"ohos:width="match_parent"/>DirectionalLayout>
代码中组件id被指定为text_field,会在下面的响应代码中用到。
获取TextField组件并取得输入文字信息
如下面代码中20行和22行所示,在按钮组件的响应代码中获取TextField组件后,获取输入的文字信息并弹窗显示。
package com.example.helloharmony.slice;import com.example.helloharmony.ResourceTable;import ohos.aafwk.ability.AbilitySlice;import ohos.aafwk.content.Intent;import ohos.agp.components.Button;import ohos.agp.components.Component;import ohos.agp.components.TextField;import ohos.agp.utils.LayoutAlignment;import ohos.agp.window.dialog.ToastDialog;public class ComponentAbilitySlice extends AbilitySlice {public void onStart(Intent intent) {super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_component);Button button = (Button) findComponentById(ResourceTable.Id_hello_button);// 为按钮设置点击事件回调button.setClickedListener(new Component.ClickedListener() {public void onClick(Component v) {TextField tf = (TextField) findComponentById(ResourceTable.Id_text_field);new ToastDialog(getContext()).setText(tf.getText()).show();}});}public void onActive() {super.onActive();}public void onForeground(Intent intent) {super.onForeground(intent);}}
画面显示如下:
参考文档
TextField类:
https://developer.harmonyos.com/cn/docs/documentation/doc-references/textfield-0000001054358710
TextField组件:
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-textfield-0000001061125582
新书介绍
《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!

