在HarmonyOS NEXT开发中弹出一个自定义弹窗,里面包含一个多行输入框,怎么让弹窗弹出的时候,输入框自动获取焦点?

在HarmonyOS NEXT开发中弹出一个自定义弹窗,里面包含一个多行输入框,怎么让弹窗弹出的时候,输入框自动获取焦点?

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

阅读 545
avatarAI BotBETA
在HarmonyOS NEXT开发中,要让自定义弹窗弹出时,其内部的多行输入框自动获取焦点,你可以通过以下步骤实现:

1. **设置弹窗显示监听**:在弹窗显示时,通过监听器来触发输入框获取焦点的操作。

2. **请求输入框获取焦点**:在弹窗显示监听器中,调用输入框的`requestFocus()`方法,使其自动获取焦点。

示例代码如下:

// 假设你的自定义弹窗类为 CustomDialog,并且包含一个 MultiLineEditText(多行输入框)
CustomDialog dialog = new CustomDialog(this);

// 设置弹窗显示监听器
dialog.setShownListener(new DialogInterface.OnShowListener() {

@Override
public void onShow(DialogInterface dialogInterface) {
    // 获取多行输入框的实例
    MultiLineEditText editText = dialog.findViewById(R.id.multi_line_edit_text);
    // 请求输入框获取焦点
    editText.requestFocus();
}

});

// 显示弹窗
dialog.show();


以上代码在弹窗显示时,通过`setShownListener`监听弹窗的显示事件,并在事件触发时调用输入框的`requestFocus()`方法,使其自动获取焦点。

请确保你的自定义弹窗类(如`CustomDialog`)和布局文件中已经正确设置了多行输入框(如`MultiLineEditText`),并且其ID与代码中获取实例时使用的ID一致。
1 个回答

在输入框上加上defaultFocus属性,即可在弹窗弹出时,输入框自动获焦

@CustomDialog 
export struct BottomCommentBoxDialog { 
  @State placeholder: string = "我来说两句" 
  onComment?: (content:string )=>void 
  @State content: string = "" 
  controller: CustomDialogController = new CustomDialogController({ 
    builder: BottomCommentBoxDialog({}), 
  }) 
  editController: TextAreaController = new TextAreaController() 
  build() { 
    Row() { 
      TextArea({ text: this.content, placeholder: this.placeholder, controller: this.editController }) 
        .fontSize(16) 
        .fontFamily("normal") 
        .fontColor(Color.Black) 
        .placeholderColor(Color.Gray) 
        .placeholderFont({ family:"normal" }) 
        .onChange((value: string) => { 
          this.content = value 
        }) 
        .maxLines(3) 
        .constraintSize({ 
          minHeight:60, 
          maxHeight:110 
        }) 
        .layoutWeight(1) 
          // 自动获焦 
        .defaultFocus(true) 
      Text("发布").fontColor(this.content.trim().length == 0 ? Color.Gray : Color.Red).fontSize(17).fontFamily("normal").padding(13).onClick(()=>{ 
        if(this.onComment){ 
          this.onComment(this.content) 
        } 
      }) 
    }.padding({ 
      left: 13, 
      top: 10, 
      bottom: 30 
    }).width('100%').backgroundColor(Color.White).borderRadius(0) 
  } 
}

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进