簡體   English   中英

每當打開AlertDialog.Builder對象時顯示軟鍵盤

[英]Displaying soft keyboard whenever AlertDialog.Builder object is opened

我打開輸入對話框的代碼如下:

final AlertDialog.Builder alert = new AlertDialog.Builder(this);  
alert.setTitle("Dialog Title");  
alert.setMessage("Request information");  
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.edittextautotextlayout, null);
final EditText inputBox = (EditText) textEntryView.findViewById(R.id.my_et_layout);
alert.setView(inputBox);

這很好用,除了我必須在軟鍵盤出現之前點擊文本輸入行。

按照這里給出的建議我嘗試插入:

inputBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            alert.getWindow().setSoftInputMode( 
               WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});

但是Eclipse對象“沒有為AlertDialog.Builder類型定義方法getWindow()”。

似乎setOnFocusChangeListener代碼適用於AlertDialog對象,但不適用於AlertDialog.Builder。 我應該如何修改我的代碼以使軟鍵盤自動顯示。

只要您始終需要在對話框打開后立即顯示鍵盤而不是一次特定的窗體小部件內部獲得焦點(例如,如果對話框只顯示EditText和按鈕),您可以執行以下操作:

AlertDialog alertToShow = alert.create();
alertToShow.getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
alertToShow.show();

不要立即在構建器上調用.show() ,而是調用.create() ,它允許您在將其顯示到屏幕上之前對其進行一些額外的處理。

這是對miannelle的回應。

選擇菜單選項時,將調用以下方法:

private void addNote() {
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.textentryalertdialog);
    dialog.setTitle("Add note");
    TextView msgText = (TextView) dialog.findViewById(R.id.messagetext);
    msgText.setText("Whatever prompt you want");
    final EditText inputLine = (EditText) dialog.findViewById(R.id.my_edittext);
    Button okButton = (Button) dialog.findViewById(R.id.OKButton);
    okButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            dialog.dismiss();
            // app specific code
        }           
    });
    Button cancelButton = (Button) dialog.findViewById(R.id.CancelButton);
    cancelButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            dialog.dismiss();
        }           
    });
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    dialog.show();
}

textentryalertdialog.xml文件定義包含的線性布局

TextView android:id =“@ + id / messagetext”......

EditText android:id =“@ + id / my_edittext”......

按鈕android:id =“@ + id / OKButton”......

按鈕android:id =“@ + id / CancelButton”...

我希望這有幫助。

在Mur Votema的鼓勵下(見上面的回答)我通過構建基於Dialog類的自定義對話框來回答我的問題。 與基於AlertDialog.Builder的警報不同,這樣的自定義對話框確實接受getWindow()。setSoftInputMode(...)命令,因此允許自動顯示軟鍵盤。

有關構建自定義對話框的指導,我找到了此網頁尤其有用。

如果你想彈出對話框和軟鍵盤,那么用戶可以免費點擊對話框內的編輯文本來顯示鍵盤,例如,如果你要從對話框中取一些值,那么使用這個簡單的代碼,它會解決你的問題。

        public void onClick(final View v) 
        {   
             AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());                 
              alert.setIcon(R.drawable.smsicon);
              alert.setTitle(" Secrete Code");  
              alert.setMessage("Enter a Key for secrete text !");
              final EditText shft_val = new EditText(v.getContext()); 
              shft_val.setInputType(InputType.TYPE_CLASS_NUMBER);//changing the keyBoard to No only,restrict the string etc
              alert.setView(shft_val);

     //pOp Up the key pad on Edit Text  focus event

             shft_val.setOnFocusChangeListener(new OnFocusChangeListener()
             {
                public void onFocusChange(View arg0, boolean arg1)
                {  InputMethodManager inputMgr = (InputMethodManager)v.getContext().
                                    getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
                        }
                    });

                 alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
                 {  
                 public void onClick(DialogInterface dialog, int whichButton) 
                 {
                    //Your specific code... 
                 }
                 });
                 alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                     public void onClick(DialogInterface dialog, int which) {                       
                         dialog.dismiss();
                         return;   
                     }
                 });
                       alert.show();
                    }

我知道,這個問題真的很老了,但是因為我已經嘗試了大約20個不同的所謂“解決方案”,我會發帖,實際上最終只對我有用。

這個答案是基於Pir Fahim Shah的答案,他指出了我正確的方向(謝謝):

確保將此值放在活動的onCreate中,以便在關閉對話框時隱藏強制鍵盤:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

然后創建一個這樣的對話框:

    AlertDialog.Builder builder = new Builder(this);
    builder.setTitle("title");
    final EditText input = new EditText(this);
    input.setText("text");
    input.setSelection(input.getText().length()); // set cursor to end
    builder.setView(input);
    input.setOnFocusChangeListener(new OnFocusChangeListener()  {
       public void onFocusChange(View v, boolean hasFocus) { 
           if(hasFocus) {
               InputMethodManager inputMgr = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
               inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
           }
       }
    });
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // do something here
            dialog.dismiss();
        }
    });
    builder.setNegativeButton("Cancel", null);
    builder.show();

嘗試使用inputBox

inputBox.getWindow().setSoftInputMode( 
               WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

嘗試使用視圖

v.getWindow().setSoftInputMode( 
           WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

您是否嘗試將焦點設置在EditText - > inputBox.requestFocus()或類似的東西上?

我創建一個AlertDialog並使用包含EditText的自定義視圖。 我希望在顯示對話框時顯示軟鍵盤,並且無論用戶單擊“確定”按鈕還是對話框外的某個位置,都要隱藏軟鍵盤。

這段代碼來自androidx.perference.PreferenceDialogFragmentCompat ,我清理了一下。

final AlertDialog.Builder builder = new AlertDialog.Builder(context)
        .setTitle(mDialogTitle)
        .setPositiveButton(mPositiveButtonText, null)
        .setNegativeButton(mNegativeButtonText, null);

View contentView = LayoutInflater.from(context).inflate(resId, null);

mEditText = contentView.findViewById(android.R.id.edit);

/**
 * From PreferenceDialogFragmentCompat.needInputMethod
 * <p>Note: If your application targets P or above, ensure your subclass manually requests
 * focus (ideally in {@link #onBindDialogView(View)}) for the input field in order to
 * correctly attach the input method to the field.
 */
mEditText.requestFocus();

builder.setView(contentView);

final Dialog dialog = builder.create();
dialog.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

// This is not from PreferenceDialogFragmentCompat and I add it.
// It seems the soft keyboard won't get dismissed on some old devices without this line.
dialog.setOnDismissListener {
    dialog.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

dialog.show();

您不需要修改Manifest。 它會自動聚焦到EditText ,無論您是單擊對話框操作按鈕還是對話框外的某個位置,它都將被解除。

我想你幾乎已經在原來的問題上工作了。 嘗試創建一個final AlertDialog來調用getWindow() ,例如

// Create the dialog used to modify the mailbox alias
final AlertDialog dialog = alert.create();

inputBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode( 
               WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});

我已經測試了這段代碼,鍵盤現在會自動顯示在我的大多數設備上,包括:

  • 三星Galaxy Tab OS 2.2
  • 三星Galaxy S OS 2.1
  • HTC Sensation OS 2.3.4

關於此解決方案的其他一些評論

1)檢查你的XML中是否有任何東西要求關注,因為這可能會阻止此代碼工作(根據你鏈接到的問題中的Ted)。

2)此代碼似乎不適用於運行OS 2.3.4的HTC G2。 我想這是因為它有一個物理鍵盤,也許WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE選項無法使用它?

我也嘗試過SOFT_INPUT_STATE_VISIBLE(沒有ALWAYS),但是這使得鍵盤自動停止顯示。

3)您可能還想添加代碼,以便用戶可以按鍵盤上的完成按鈕來提交更改,例如

inputAlias.setOnKeyListener(new OnKeyListener()
{
  @Override
  public boolean onKey(View v, int keyCode, KeyEvent event)
  {
    if (keyCode == KeyEvent.KEYCODE_ENTER &&
        inputAlias.isFocused() &&
        inputAlias.getText().length() != 0)
    {
      // Save the new information here

  // Dismiss the dialog
      dialog.dismiss();
      return true;
    }
    return false;
  }
});

在下面的代碼片段中,我將展示如何在DialogFragment托管任意LinearLayout 一個使用AlertDialog (軟鍵盤不起作用)和另一種不使用AlertDialog (軟鍵盤工作的方式!):

public static LinearLayout createLinearLayout(Context context)
{
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    String html;
    html = "<form action=search method=get >\n";
    html += "Google Search: <input name=q value=\"Johnny Depp\" /><br/>\n";
    html += "<input type=submit name=output value=search /><br/>\n";
    html += "</form>\n";
    WebView webView = new WebView(context);
    webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient());
    webView.loadDataWithBaseURL("http://www.google.com", html, "text/html", "UTF-8", null);
    linearLayout.addView(webView);
    return linearLayout;
}

public void showWithAlertDialog()
{
    DialogFragment dialogFragment = new DialogFragment()
    {
        public Dialog onCreateDialog(Bundle savedInstanceState)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder
                .setTitle("With AlertDialog")
                .setView(createLinearLayout(getActivity()));
            return builder.create();
        }
    };
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    dialogFragment.show(fragmentTransaction, "dialog");
}

public void showWithoutAlertDialog()
{
    DialogFragment dialogFragment = new DialogFragment()
    {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            getDialog().setTitle("Without AlertDialog");
            getDialog().setCanceledOnTouchOutside(false);
            return createLinearLayout(getActivity());
        }
    };
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    dialogFragment.show(fragmentTransaction, "dialog");
}

我發現這可以在一個叫來自不同地方的警報對話框中工作

        case R.id.birthyear:
        case R.id.ymax:
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            break;

請注意,我也嘗試了很多其他的東西。 看起來很精致。

.setView()將在對話框中自動調出鍵盤。 注意EditText本身的“final”。 重要!

AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Random Title...");
alert.setMessage("Type a name");

final EditText input = new EditText(this);

//Set input focus (which opens the android  soft keyboard)
alert.setView(input);   
input.setHint("My Name is...");
//Set keyboard type
input.setInputType(InputType.TYPE_CLASS_TEXT); 

//add button onclick handlers...

alert.show();

我認為很多人都對所有功能都過度了...這是相當普遍的,而且效果很好。 它不會膨脹您的代碼。

嗨,Prepbgg實際上有一種替代方式來完成你的工作。 我實際上不得不在我的ArrayAdapter中使用我的。 我所做的是將活動的上下文傳遞給arrayadapter,然后調用它來訪問getWindow(),如下所示:

NoteArrayAdapter(Activity _activity, int _layout, ArrayList<Note> _notes, Context _context) {
  callingNoteListObj = (NoteList) _context;
}

// withiin getView

callingNoteListObj.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

// within parent activity's onCreate()
thisObject = this;

//within my parent activity's fillData() (NoteList)
adapter =  new NoteArrayAdapter(activity, R.layout.channel_note_list_item, noteList, thisObject);

暫無
暫無

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

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