1# 在自绘编辑框中使用输入法 2 3在输入法框架中,可以通过[getController](../reference/apis-ime-kit/js-apis-inputmethod.md#inputmethodgetcontroller9)方法获取到[InputMethodController](../reference/apis-ime-kit/js-apis-inputmethod.md#inputmethodcontroller)实例来绑定输入法并监听输入法应用的各种操作,比如插入、删除、选择、光标移动等。这样就可以在自绘编辑框中使用输入法,并实现更加灵活和自由的编辑操作。 4 5## 开发步骤 6 71. 开发者在自绘编辑框使用输入法时,首先需要在DevEco Studio工程中新建一个ets文件,命名为自定义控件的名称,本示例中命名为CustomInput,在文件中定义一个自定义控件,并从@kit.IMEKit中导入inputMethod。 8 9 ```ets 10 import { inputMethod } from '@kit.IMEKit'; 11 12 @Component 13 export struct CustomInput { 14 build() { 15 } 16 } 17 ``` 18 192. 在控件中,使用Text组件作为自绘编辑框的文本显示组件,使用状态变量inputText作为Text组件要显示的内容。 20 21 ```ets 22 import { inputMethod } from '@kit.IMEKit'; 23 24 @Component 25 export struct CustomInput { 26 @State inputText: string = ''; // inputText作为Text组件要显示的内容。 27 28 build() { 29 Text(this.inputText) // Text组件作为自绘编辑框的文本显示组件。 30 .fontSize(16) 31 .width('100%') 32 .lineHeight(40) 33 .id('customInput') 34 .height(45) 35 .border({ color: '#554455', radius: 30, width: 1 }) 36 .maxLines(1) 37 } 38 } 39 ``` 40 413. 在控件中获取inputMethodController实例,并在文本点击时调用controller示例的attach方法绑定和拉起软键盘,并注册监听输入法插入文本、删除等方法,本示例仅展示插入、删除。 42 43 ```ets 44 import { inputMethod } from '@kit.IMEKit'; 45 46 @Component 47 export struct CustomInput { 48 @State inputText: string = ''; // inputText作为Text组件要显示的内容。 49 private isAttach: boolean = false; 50 private inputController: inputMethod.InputMethodController = inputMethod.getController(); 51 52 build() { 53 Text(this.inputText) // Text组件作为自绘编辑框的文本显示组件。 54 .fontSize(16) 55 .width('100%') 56 .lineHeight(40) 57 .id('customInput') 58 .onBlur(() => { 59 this.off(); 60 }) 61 .height(45) 62 .border({ color: '#554455', radius: 30, width: 1 }) 63 .maxLines(1) 64 .onClick(() => { 65 this.attachAndListener(); // 点击控件 66 }) 67 } 68 69 async attachAndListener() { // 绑定和设置监听 70 focusControl.requestFocus('CustomInput'); 71 await this.inputController.attach(true, { 72 inputAttribute: { 73 textInputType: inputMethod.TextInputType.TEXT, 74 enterKeyType: inputMethod.EnterKeyType.SEARCH 75 } 76 }); 77 if (!this.isAttach) { 78 this.inputController.on('insertText', (text) => { 79 this.inputText += text; 80 }) 81 this.inputController.on('deleteLeft', (length) => { 82 this.inputText = this.inputText.substring(0, this.inputText.length - length); 83 }) 84 this.isAttach = true; 85 } 86 } 87 88 off() { 89 this.isAttach = false; 90 this.inputController.off('insertText') 91 this.inputController.off('deleteLeft') 92 } 93 } 94 ``` 95 964. 在应用界面布局中引入该控件即可,此处假设使用界面为Index.ets和控件CustomInput.ets在同一目录下。 97 98 ```ets 99 import { CustomInput } from './CustomInput'; // 导入控件 100 101 @Entry 102 @Component 103 struct Index { 104 105 build() { 106 Column() { 107 CustomInput() // 使用控件 108 } 109 } 110 } 111 ``` 112 113 ## 示例效果图 114 