簡體   English   中英

AlertDialog - 顯示帶有自定義類的軟鍵盤不起作用

[英]AlertDialog - Show soft keyboard with a custom class not working

我的問題是我的自定義 alertdialog 類沒有正確顯示軟鍵盤。 我正在使用

SettingsDialog settingsDialog = new SettingsDialog(MainActivity.this);
settingsDialog.show();

並且軟鍵盤沒有顯示。 我已經按照其他 stackoverflow 的答案來顯示鍵盤... Show soft keyboard for dialog

如果我不使用自定義類,它會起作用

AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setView(R.layout.alertdialog_settings);
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();

在此處輸入圖片說明

但是,當使用自定義 AlertDialog 類時,我似乎無法獲得與上圖相同的結果

我試過手動顯示鍵盤

SettingsDialog settingsDialog = new SettingsDialog(MainActivity.this);
settingsDialog.show();
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
   imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}

在此處輸入圖片說明

然而,它顯示了alertdialog 后面的鍵盤,並且不會產生與AlertDialog Builder 相同的效果。

如何使用自定義 AlertDialog 顯示軟鍵盤以具有使用 AlertDialog Builder 的輸出?

編輯:

我也嘗試在 AlertDialog 的 onCreate 方法中手動顯示它

public class SettingsDialog extends AlertDialog {
     public SettingsDialog(@NonNull Context context, String subName) {
            super(context);
            this.mContext = context;
            this.mSubName = subName;

     }

     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alertdialog_settings);

        InputMethodManager imm = (InputMethodManager) 
        mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm != null){
          imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
        }

     }
}

但是,這仍然會導致鍵盤顯示在 alertDialog 后面

我嘗試了許多其他方法,但這個方法終於奏效了。

SortByDialog sortByDialog = new SortByDialog(MainActivity.this);
sortByDialog.show();
sortByDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

需要確保 clearFlags 在您的自定義 AlertDialogClass 的.show()之后

我認為您不需要擴展 Alert Dialog 類,您可以做的只是一個包含幫助函數的自定義 java 來創建您的自定義對話框,因此您仍然可以進行代碼抽象並可以輕松添加其他功能。

public class SettingsDialog  {

  private  AlertDialog.Builder mBuilder = null;
  private  AlertDialog alertDialog = null;

 public SettingsDialog(@NonNull Context context, String subName) {
        this.mSubName = subName;
        this.mContext = context;
 }

 public show(){
    mBuilder = new AlertDialog.Builder(mContext);
    mBuilder.setView(R.layout.someID);
    alertDialog = mBuilder.create();
    alertDialog.show();
 }

 public void dismiss(){
    if(alertDialog == null) return;
    alertDialog.dismiss();
 }

 // can use interface to handle callbacks

}


// usage 

SettingsDialog sd = new SettingsDialog(this, "MATHS");
sd.show();
//sd.dismiss();

嘗試延遲顯示鍵盤 е.g. 對話框創建后 100-200 毫秒,或者只是嘗試使用 EditText.requestFocus() 請求對話框的 EditText 焦點也在對話框創建后延遲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM