仓颉 ArkUI 文本输入组件实战:TextInput 与 TextArea 的创建、样式、事件与键盘避让
仓颉 ArkUI 文本输入组件实战:TextInput 与 TextArea 的创建、样式、事件与键盘避让
本文聚焦 OpenHarmony 仓颉(Cangjie)应用开发中 ArkUI 声明式 UI 的文本输入组件,系统讲解单行输入框 TextInput 与多行输入框 TextArea 的创建方式、样式定制、选中菜单、事件回调与控制器用法,并给出键盘避让的完整工程示例。读完本文,你将掌握用仓颉语言快速搭建登录页、评论框、聊天输入框等常见输入场景的完整技术方案。
组件概述:单行 TextInput 与多行 TextArea
TextInput、TextArea 是 ArkUI 中面向仓颉语言的输入框组件,通常用于响应用户的输入操作,例如评论区的输入、聊天框的输入、表格的输入等,也可以结合其它组件构建功能页面,例如登录注册页面。两者的核心区别在于:
- TextInput:单行文本输入框,回车键默认作为提交/确认动作(对应
EnterKeyType.Done)。 - TextArea:多行文本输入框,当输入的文本内容超过组件宽度时会自动换行显示。高度未设置时组件无默认高度、自适应内容高度;宽度未设置时默认撑满最大宽度。
两个组件的完整接口定义可参考 TextInput API 与 TextArea API。在仓颉代码中,使用前需要导入 ArkUI 模块:
import kit.ArkUI.*
两者的 init 构造接口签名几乎一致,均包含占位符文本、当前文本内容和组件控制器三个命名参数:
init(placeholder!: ?ResourceStr = None, text!: ?ResourceStr = None, controller!: ?TextInputController = None)
init(placeholder!: ?ResourceStr = None, text!: ?ResourceStr = None, controller!: ?TextAreaController = None)
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| placeholder | ?ResourceStr |
否 | None | 命名参数。 占位符文本,无输入时显示的文本 |
| text | ?ResourceStr |
否 | None | 命名参数。 输入框的当前值 |
| controller | ?TextInputController / ?TextAreaController |
否 | None | 命名参数。 输入框组件的控制器 |
其中 ResourceStr 为字符串资源类型,可传入普通字符串或资源引用,定义见 cj-common-types.md。两组件均支持全部通用属性与通用事件,详见 通用属性。
创建输入框
创建单行输入框
直接使用无参构造即可得到一个默认样式的单行输入框:
TextInput()
创建多行输入框
TextArea()
多行输入框的自动折行
TextArea 的文字超出一行时会自动折行,在指定宽度下可以直观看到该行为:
TextArea(text: "我是TextArea我是TextArea我是TextArea我是TextArea" ).width(300)
上述代码通过 .width(300) 限定宽度为 300 个默认单位,超出的文字会换到下一行显示,这正是多行输入框与单行输入框最直观的行为差异。
自定义样式
设置占位符提示文本
无输入时显示的提示文本通过 placeholder 命名参数设置:
TextInput(placeholder: '我是提示文本')
设置当前文本内容
通过 text 参数直接预置输入框内容:
TextInput( placeholder: '我是提示文本', text: '我是当前文本内容' )
修改背景颜色
背景颜色属于通用属性,通过链式调用 .backgroundColor() 修改:
TextInput( placeholder: '我是提示文本', text: '我是当前文本内容' )
.backgroundColor(0xFEC0CD)
更多通用属性(如 width、height、margin、padding、border、borderRadius、size 等)可以结合 通用属性文档 灵活使用,实现圆角、边框、阴影等更丰富的视觉效果。
输入框专属样式属性
除了通用属性,TextInput/TextArea 还提供了一组组件专属样式属性,用于精细化控制占位符、光标、字体与对齐方式。下表汇总了常用属性的签名与默认值(详见两篇参考文档):
| 属性方法 | 功能说明 | 默认值 |
|---|---|---|
caretColor(value: ?ResourceColor) |
设置光标的颜色 | 0xFF007DFF |
placeholderColor(value: ?ResourceColor) |
设置占位符文本的颜色 | 跟随主题 |
placeholderFont(size!:, weight!:, family!:, style!:) |
设置占位符文本的字体大小、粗细、字体族与样式 | size 为 (-1.0).px、weight 为 FontWeight.W400 |
fontSize(value: ?Length) |
设置文本的字体大小 | TextInput 默认 16.fp 级别,TextArea 为 16.fp |
fontColor(value: ?ResourceColor) |
设置文本的颜色 | TextInput 默认 0xdbffffff |
fontFamily(value: ?ResourceStr) |
设置文本的字体族 | "HarmonyOS Sans" |
fontStyle(value: ?FontStyle) |
设置文本的字体样式(Normal/Italic 等) | FontStyle.Normal |
fontWeight(value: ?FontWeight) |
设置文本的字体粗细(W100~W900) | FontWeight.Normal |
textAlign(value: ?TextAlign) |
设置文本的水平对齐方式 | TextAlign.Start |
maxLength(value: ?UInt32) |
设置文本的最大长度 | 无限制 |
maxLines(value: ?Int32) |
定义文本输入的最大行数(TextInput 可用) | 3 |
showUnderline(value: ?Bool) |
定义是否显示文本输入的下划线 | false |
selectionMenuHidden(value: ?Bool) |
控制选中菜单是否弹出 | false |
style(value: ?TextInputStyle) |
文本输入风格(Default/Inline) | TextInputStyle.Default |
其中 EnterKeyType、FontStyle、FontWeight、TextAlign、TextInputStyle 等枚举均定义在 cj-common-types.md。以 style 属性为例,TextInputStyle.Default 表示默认风格(光标宽 1.5.vp,光标高度与文本选中底板高度和字体大小相关),而 TextInputStyle.Inline 表示内联输入风格,文本选中底板高度与输入框高度相同,适用于需要明显区分编辑与非编辑状态的场景(如文件列表中的重命名),内联模式不支持 showError 属性,也不支持拖入文本。
输入过滤与长度限制
inputFilter(value: ?ResourceStr, error!: ?(String) -> Unit = None) 用于设置输入过滤规则,value 为正则表达式字符串,不符合规则的输入会被拦截;error 为命名参数,输入错误时回调。例如限制只允许小写字母:
TextInput()
.inputFilter('[a-z]', error: { info: String =>
Hilog.error(0, "AppLogCj", "inputFilter error")
})
配合 maxLength 可限制输入长度,典型场景是密码框:
// 密码输入框
TextInput(placeholder: 'input your password...')
.maxLength(9)
输入框事件
onChange:内容变化监听
输入框内容发生变化时触发,回调参数为当前文本值。这是将输入框与状态管理绑定的核心事件,可配合 @State 实时同步数据:
@State var text: String = ''
TextInput(text: this.text, placeholder: 'input your word...')
.onChange({ value: String =>
this.text = value
})
Text(this.text) // 输入内容实时回显
onSubmit:提交事件
用户点击软键盘的输入按钮(如 Done/Search/Send)时触发,回调参数为 EnterKeyType。EnterKeyType 枚举(见 cj-common-types.md)提供 Go、Search、Send、Next、Done、Previous、NewLine 等取值;TextInput 默认 EnterKeyType.Done,TextArea 默认 EnterKeyType.NewLine。提交事件的典型用法:
TextInput(placeholder: '请输入搜索关键词')
.enterKeyType(EnterKeyType.Search)
.onSubmit({ val =>
// 触发搜索逻辑
})
剪贴板事件
选中菜单触发剪切、复制、粘贴操作时,分别回调 onCut、onCopy、onPaste,回调参数为操作涉及的文本内容:
TextArea(placeholder: "TextArea callback")
.onChange({ val => Hilog.info(0, "cangjie", "TextArea onChange:" + val) })
.onPaste({ val => Hilog.info(0, "cangjie", "TextArea onPaste:" + val) })
.onCut({ val => Hilog.info(0, "cangjie", "TextArea onCut:" + val) })
.onCopy({ val => Hilog.info(0, "cangjie", "TextArea onCopy:" + val) })
.onSubmit({ val => Hilog.info(0, "cangjie", "TextArea onSubmit") })
onEditChange:编辑状态变化
文本编辑状态(进入/退出编辑)发生变化时回调,参数为 Bool,可用于联动 UI 状态。
使用控制器精确控制输入框
TextInput 与 TextArea 分别提供 TextInputController 与 TextAreaController 控制器类(定义见 TextInput 参考文档 与 TextArea 参考文档),将控制器对象绑定到组件的 controller 参数后,即可在组件外部调用其方法:
var controller: TextInputController = TextInputController()
TextInput(text: this.text, placeholder: 'input your word...', controller: this.controller)
设置光标位置
caretPosition(value: ?Int32) 用于设置插入光标的位置,参数为从字符串开始到光标位置的长度:
controller.caretPosition(3) // 将光标移动到第 3 个字符之后
文本选择与菜单策略
TextInputController 还提供了 setTextSelection(selectionStart: ?Int32, selectionEnd: ?Int32, options!: ?MenuPolicy = None),通过指定文本的起始和结束位置实现程序化文本选择。其中 options 为 MenuPolicy 枚举(见 cj-common-types.md):
| 枚举值 | 说明 |
|---|---|
MenuPolicy.Default |
按照底层默认逻辑决定是否弹出菜单 |
MenuPolicy.Hide |
始终不弹出菜单 |
MenuPolicy.Show |
始终弹出菜单 |
退出编辑状态
stopEditing() 用于退出编辑状态,例如在点击页面空白区域或提交完成后收起输入焦点。
选中菜单
输入框中的文字被选中时会自动弹出包含剪切、复制、翻译的菜单。TextInput 与 TextArea 行为一致:
TextInput( text: '这是一段文本,用来展示选中菜单')
TextArea( text: '这是一段文本,用来展示选中菜单')
如需禁用该菜单,可设置 .selectionMenuHidden(true)。若希望在选择文本时精确控制菜单的弹出策略,也可以结合控制器的 setTextSelection 与 MenuPolicy 配合实现。
键盘避让
键盘抬起后,具有滚动能力的容器组件在横竖屏切换时才会生效键盘避让。若希望无滚动能力的容器组件也生效键盘避让,建议在组件外层嵌套一层具有滚动能力的容器组件,例如 Scroll、List、Grid。
以下是一个完整的可运行工程示例,通过 Scroll 包裹多个 TextInput,确保软键盘弹出时输入框不会被遮挡:
package ohos_app_cangjie_entry
import kit.ArkUI.*
import ohos.arkui.state_macro_manage.*
@Entry
@Component
class EntryView {
var placeHolderArr: Array<String> = ["1", "2", "3", "4", "5", "6", "7"];
func build() {
Scroll() {
Column {
ForEach(this.placeHolderArr, itemGeneratorFunc: {placeholder: String, _: Int64 =>
TextInput( placeholder: 'TextInput ' + placeholder )
.margin(30)}
)
}
}
.height(100.percent)
.width(100.percent)
}
}
要点说明:
Scroll容器撑满整个页面(.height(100.percent).width(100.percent)),内部Column依次排列多个TextInput;- 每个输入框通过
.margin(30)增加间距,便于观察键盘避让效果; - 使用
ForEach基于placeHolderArr数组批量生成输入框,占位符动态拼接为'TextInput ' + placeholder; - 当软键盘抬起时,
Scroll容器会自动调整内容滚动位置,保证当前聚焦的输入框可见。
综合实战:登录表单
综合以上知识点,可以构建一个带实时回显、输入过滤与提交处理的登录表单雏形:
package ohos_app_cangjie_entry
import kit.ArkUI.*
import ohos.hilog.*
import ohos.arkui.state_macro_manage.*
@Entry
@Component
class EntryView {
@State var text: String = ''
@State var passwordState: Bool = false
var controller: TextInputController = TextInputController()
func build() {
Column() {
TextInput(text: this.text, placeholder: 'input your word...', controller: this.controller)
.placeholderColor(Color.Gray)
.placeholderFont(size: 14, weight: FontWeight.W100)
.caretColor(Color.Blue)
.width(95.percent)
.height(40)
.margin(20)
.fontSize(14)
.fontColor(Color.Black)
.inputFilter('[a-z]', error: { info: String =>
Hilog.error(0, "AppLogCj", "inputFilter error")
})
.onChange({ value: String =>
this.text = value
})
Text(this.text)
Button('Set caretPosition 1')
.margin(15)
// 密码输入框
TextInput(placeholder: 'input your password...')
.width(95.percent)
.height(40)
.margin(20)
.maxLength(9)
// 内联风格输入框
TextInput( text: 'inline style' )
.width(95.percent)
.height(50)
.margin(20)
.borderRadius(0)
.style(TextInputStyle.Inline)
}.
width(100.percent)
}
}
该示例(来源参考 TextInput 参考文档示例)演示了占位符字体、光标颜色、输入过滤回调、内容实时回显、控制器绑定与内联输入风格等完整能力,可作为登录、注册、搜索等页面的基础模板。
总结
本文围绕仓颉 ArkUI 的 TextInput 与 TextArea 组件,覆盖了从基础创建、样式定制、事件监听、控制器精确控制到键盘避让的完整使用链路。核心要点可归纳为:
- TextInput 单行、TextArea 多行自动折行,
init构造统一接收placeholder、text、controller三个命名参数; - 样式定制既可通过通用属性(
backgroundColor、width、margin等)实现,也可通过组件专属属性(placeholderColor、placeholderFont、caretColor、fontSize、textAlign、style、showUnderline等)精细控制; - 输入控制依靠
maxLength、inputFilter(正则 + 错误回调)与enterKeyType完成; - 事件体系包含
onChange、onSubmit、onCopy、onCut、onPaste、onEditChange,覆盖内容变化、提交与剪贴板操作; - 控制器(
TextInputController/TextAreaController)支持caretPosition、setTextSelection、stopEditing,实现程序化光标定位与文本选择; - 键盘避让依赖外层滚动容器(Scroll/List/Grid),无滚动能力容器需自行嵌套一层滚动容器。