一、簡介

ArkUI的彈出框焦點策略可以設定是否中斷用户當前操作,並聚焦到新彈出的彈出框。若設定彈出框不獲取焦點,則新彈出時不會中斷用户當前操作,例如,當用户正在文本框中輸入內容時,新彈出的彈出框不會關閉軟鍵盤,焦點仍保留在文本框中。
API version 19開始,可以通過設置focusable參數來管理彈出框是否獲取焦點。

二、使用約束

openCustomDialog和CustomDialog支持通過focusable參數來管理彈出框是否獲取焦點。
説明 只有彈出覆蓋在當前窗口之上的彈出框才可以獲取焦點。

三、創建不獲取焦點的彈出框

  1. 初始化一個彈出框內容區域,內含一個Text組件。
private message = '彈窗'
@State dialogIdIndex: number = 0
@Builder customDialogComponent() {
  Column({ space: 5 }) {
    Text(this.message + this.dialogIdIndex)
      .fontSize(30)
  }
  .height(200)
  .padding(5)
  .justifyContent(FlexAlign.SpaceBetween)
}
  1. 創建一個TextInput組件,在onChange事件函數中通過調用UIContext中的getPromptAction方法獲取PromptAction對象,再通過該對象調用openCustomDialog接口,並設置focusable參數為false,以創建彈出框。
TextInput()
  .onChange(() => {
    this.dialogIdIndex++
    this.getUIContext().getPromptAction().openCustomDialog({
      builder: () => {
        this.customDialogComponent()
      },
      focusable: false
    }).then((dialogId: number) => {
      setTimeout(() => {
        this.getUIContext().getPromptAction().closeCustomDialog(dialogId);
      }, 3000)
    })
  })

四、完整示例

當用户正在文本框中輸入內容時,新彈出的彈出框不會關閉軟鍵盤,焦點仍保留在文本框中。

效果圖

HarmonyOS:彈出框焦點策略_HarmonyOS

示例代碼

@Entry
@Component
export struct TestOpenCustomDialog6 {
  private message = '彈窗不獲取焦點';
  @State dialogIdIndex: number = 0;

  @Builder
  customDialogComponent() {
    Column({ space: 5 }) {
      Text(this.message + this.dialogIdIndex)
        .fontSize(30)
    }
    .height(200)
    .padding(5)
    .justifyContent(FlexAlign.SpaceBetween)
  }

  build() {
    Column({ space: 5 }) {
      TextInput()
        .onChange(() => {
          this.dialogIdIndex++;
          this.getUIContext().getPromptAction().openCustomDialog({
            builder: () => {
              this.customDialogComponent()
            },
            focusable: false// 從API version 19開始,可以通過設置focusable參數來管理彈出框是否獲取焦點。
          }).then((dialogId: number) => {
            setTimeout(() => {
              this.getUIContext().getPromptAction().closeCustomDialog(dialogId);
            }, 3000)
          })
        })
    }.width('100%')
  }
}