簡體   English   中英

Android:焦點在 EditText 上時自動顯示軟鍵盤

[英]Android: show soft keyboard automatically when focus is on an EditText

我正在使用AlertDialog顯示輸入框。 當我調用AlertDialog.show()時,對話框本身內的EditText會自動聚焦,但不會自動顯示軟鍵盤。

如何讓軟鍵盤在顯示對話框時自動顯示? (並且沒有物理/硬件鍵盤)。 類似於當我按下搜索按鈕調用全局搜索時,軟鍵盤會自動顯示。

您可以在AlertDialogEditText上創建一個焦點偵聽AlertDialog ,然后獲取AlertDialogWindow 從那里您可以通過調用setSoftInputMode顯示軟鍵盤。

final AlertDialog dialog = ...;

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

用於顯示鍵盤使用:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

隱藏鍵盤使用:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 

您可以在創建對話框后立即請求軟鍵盤(在 SDK 上測試 - r20)

// create dialog
final AlertDialog dialog = ...; 

// request keyboard   
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

我遇到了同樣的問題並使用以下代碼解決了它。 我不確定它在帶有硬件鍵盤的手機上的表現如何。

// TextEdit
final EditText textEdit = new EditText(this);

// Builder
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter text");
alert.setView(textEdit);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String text = textEdit.getText().toString();
        finish();
    }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
});

// Dialog
AlertDialog dialog = alert.create();
dialog.setOnShowListener(new OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
    }
});

dialog.show();

我發現這個例子http://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html alert.show()之前添加以下代碼。

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

或者

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

來自其他答案的代碼片段有效,但將它們放在代碼中的位置並不總是很明顯,特別是如果您使用AlertDialog.Builder並遵循官方對話框教程,因為它不使用final AlertDialog ...alertDialog.show()

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

更可取

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

因為 SOFT_INPUT_STATE_ALWAYS_VISIBLE 將在焦點從 EditText 切換時隱藏鍵盤,其中 SHOW_FORCED 將保持鍵盤顯示直到它被明確關閉,即使用戶返回主屏幕或顯示最近的應用程序。

下面是使用自定義布局創建的 AlertDialog 的工作代碼,其中 EditText 在 XML 中定義。 它還將鍵盤設置為具有“go”鍵並允許它觸發正按鈕。

警報對話框.xml:

<RelativeLayout
android:id="@+id/dialogRelativeLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <!-- android:imeOptions="actionGo" sets the keyboard to have a "go" key instead of a "new line" key. -->
    <!-- android:inputType="textUri" disables spell check in the EditText and changes the "go" key from a check mark to an arrow. -->
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:imeOptions="actionGo"
        android:inputType="textUri"/>

</RelativeLayout>

警報對話框.java:

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

public class CreateDialog extends AppCompatDialogFragment {
    // The public interface is used to send information back to the activity that called CreateDialog.
    public interface CreateDialogListener {
        void onCreateDialogCancel(DialogFragment dialog);    
        void onCreateDialogOK(DialogFragment dialog);
    }

    CreateDialogListener mListener;

    // Check to make sure that the activity that called CreateDialog implements both listeners.
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (CreateDialogListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement CreateDialogListener.");
        }
    }

    // onCreateDialog requires @NonNull.
    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        LayoutInflater customDialogInflater = getActivity().getLayoutInflater();

        // Setup dialogBuilder.
        alertDialogBuilder.setTitle(R.string.title);
        alertDialogBuilder.setView(customDialogInflater.inflate(R.layout.alert_dialog, null));
        alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogCancel(CreateDialog.this);
            }
        });
        alertDialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogOK(CreateDialog.this);
            }
        });

        // Assign the resulting built dialog to an AlertDialog.
        final AlertDialog alertDialog = alertDialogBuilder.create();

        // Show the keyboard when the dialog is displayed on the screen.
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        // We need to show alertDialog before we can setOnKeyListener below.
        alertDialog.show();

        EditText editText = (EditText) alertDialog.findViewById(R.id.editText);

        // Allow the "enter" key on the keyboard to execute "OK".
        editText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button, select the PositiveButton "OK".
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Trigger the create listener.
                    mListener.onCreateDialogOK(CreateDialog.this);

                    // Manually dismiss alertDialog.
                    alertDialog.dismiss();

                    // Consume the event.
                    return true;
                } else {
                    // If any other key was pressed, do not consume the event.
                    return false;
                }
            }
        });

        // onCreateDialog requires the return of an AlertDialog.
        return alertDialog;
    }
}

嗯,這是一個很老的帖子,仍然有一些東西要補充。
這些是 2 種簡單的方法,可以幫助我控制鍵盤,並且它們工作得非常完美:

顯示鍵盤

public void showKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.showSoftInput(v, 0);
}

隱藏鍵盤

public void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

讓我為 yuku 的解決方案提供一些額外的信息,因為我發現它很難讓它工作! 如何從 AlertDialog.Builder 獲取 AlertDialog 對象? 好吧,這是我的alert.show()執行的結果:

final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
alert.setView(input);

// do what you need, like setting positive and negative buttons...

final AlertDialog dialog = alert.show();

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

我知道這個問題很老,因為我認為使用擴展功能是顯示編輯文本鍵盤的更好方法

這是我用來顯示編輯文本鍵盤的方法。

kotlin 代碼:只需要調用edittext.showKeyboard()

fun EditText.showKeyboard() {
  post {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
  }
}

Java代碼:

public static void showKeyboard(EditText editText) {
    editText.post(new Runnable() {
      @Override
      public void run() {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) editText.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
      }
    });
  }

看看這個處理手動隱藏和顯示 IME 的討論。 但是,我的感覺是,如果聚焦的EditText沒有啟動 IME,那是因為您在OnCreate()中調用AlertDialog.show() OnCreate()或在實際顯示屏幕之前調用的其他一些方法。 在這種情況下,我相信將它移動到OnPostResume()應該可以解決它。

是的,您可以使用setOnFocusChangeListener來幫助您。

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

如果有人得到:

無法從類型 Activity 對非靜態方法 getSystemService(String) 進行靜態引用

嘗試向 getSystemService 調用添加上下文

所以

InputMethodManager imm = 
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

我們可以在對話顯示使用時默認打開鍵盤

dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)

問題似乎是,由於您輸入文本的位置最初是隱藏的(或嵌套的或其他內容),因此 AlertDialog 會自動設置標志WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IMWindowManager.LayoutParams.FLAG_NOT_FOCUSABLE以便事物不會觸發軟輸入現身。

解決此問題的方法是添加以下內容:

(...)
// Create the dialog and show it
Dialog dialog = builder.create()
dialog.show();

// After show (this is important specially if you have a list, a pager or other view that uses a adapter), clear the flags and set the soft input mode
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

嘗試使用:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

為了顯示鍵盤,對我來說,我必須執行以下操作

Android TextField:以編程方式設置焦點+軟輸入

基本上解決方案如下

@Override
public void onResume() {
    super.onResume();
    //passwordInput.requestFocus(); <-- that doesn't work
    passwordInput.postDelayed(new ShowKeyboard(), 325); //250 sometimes doesn't run if returning from LockScreen
}

ShowKeyboard在哪里

private class ShowKeyboard implements Runnable {
    @Override
    public void run() {
        passwordInput.setFocusableInTouchMode(true);
        //passwordInput.requestFocusFromTouch(); //this gives touch event to launcher in background -_-
        passwordInput.requestFocus();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
    }
}

成功輸入后,我還確保我隱藏了鍵盤

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getView().getWindowToken(), 0);

將這些方法放在您的 Util 類中並在任何地方使用。

科特林

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

爪哇

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}

我創建了很好的 kotlin-esqe 擴展函數,以防有人感興趣

fun Activity.hideKeyBoard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

fun Activity.showKeyboard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

嘗試了很多,但這對我有用(kotlin):

        val dialog = builder.create()
        dialog.setOnShowListener {
            nameEditText.requestFocus()
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }

        dialog.setOnDismissListener {
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }

        dialog.show()

只需將此行添加到清單文件必要的活動。

android:windowSoftInputMode="stateVisible"

最初的問題與對話框有關,而我的 EditText 位於常規視圖中。 無論如何,我懷疑這也適用於你們大多數人。 所以這對我有用(上面建議的最高評價方法對我沒有任何作用)。 這是一個執行此操作的自定義 EditView(子類化不是必需的,但我發現它對我的目的很方便,因為我還想在視圖可見時抓住焦點)。

這實際上與花絮的答案大致相同。 我實際上根本沒有注意到他的回答,因為它的票數為零。 然后我正要評論他的帖子,但是太長了,所以我還是結束了這篇文章。 tidbeck 指出,他不確定它如何與帶有鍵盤的設備配合使用。 我可以確認兩種情況下的行為似乎完全相同。 因此,在縱向模式下,軟件鍵盤會彈出,而在橫向模式下則不會。 物理鍵盤是否滑出對我的手機沒有影響。

因為,我個人覺得我選擇使用的行為有點尷尬: InputMethodManager.SHOW_FORCED 這可以正常工作。 無論方向如何,鍵盤都變得可見,但是,至少在我的設備上,如果硬件鍵盤已滑出,它不會彈出。

import android.app.Service;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class BringOutTheSoftInputOnFocusEditTextView extends EditText {

    protected InputMethodManager inputMethodManager;

    public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BringOutTheSoftInputOnFocusEditTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        this.inputMethodManager = (InputMethodManager)getContext().getSystemService(Service.INPUT_METHOD_SERVICE);
        this.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    BringOutTheSoftInputOnFocusEditTextView.this.inputMethodManager.showSoftInput(BringOutTheSoftInputOnFocusEditTextView.this, InputMethodManager.SHOW_FORCED);
                }
            }
        });
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == View.VISIBLE) {
            BringOutTheSoftInputOnFocusEditTextView.this.requestFocus();
        }
    }

}

這對您來說是很好的示例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollID"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="true"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:weightSum="1" >

        <EditText
            android:id="@+id/txtInpuConversation"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:hint="@string/edt_Conversation" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/btnSend"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/btn_Conversation" />
    </LinearLayout>

</LinearLayout>

為什么這個答案 - 因為上面的解決方案會顯示你的鍵盤,但如果你點擊EditText任何地方,它不會消失。 因此,當EditText失去焦點時,您需要做一些事情使 keybaord 消失。

您可以通過執行以下步驟來實現此目的:

  1. 通過添加以下屬性使父視圖(活動的內容視圖)可點擊和聚焦

     android:clickable="true" android:focusableInTouchMode="true"
  2. 實現一個 hideKeyboard() 方法

     public void hideKeyboard(View view) { InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY ); }
  3. 最后,設置您的編輯文本的 onFocusChangeListener。

     edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideKeyboard(v); } } });

這有點棘手。 我就是這樣做的,而且奏效了。

1.首先調用從窗口隱藏軟輸入。 如果軟鍵盤可見,這將隱藏軟輸入,否則將不執行任何操作。

2.顯示你的對話框

3.然后只需調用切換軟輸入。

代碼:

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWind‌​owToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);

嘗試這個

SomeUtils.java

 public static void showKeyboard(Activity activity, boolean show) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if(show) inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); else inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0); }
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

當我進入活動時,我在 onCreate() 中調用它以自動顯示鍵盤。

查看https://stackoverflow.com/a/39144104/2914140我簡化了一點:

// In onCreateView():
view.edit_text.run {
    requestFocus()
    post { showKeyboard(this) }
}

fun showKeyboard(view: View) {
    val imm = view.context.getSystemService(
        Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    imm?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

它比https://stackoverflow.com/a/11155404/2914140 好

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

因為當您按下 Home 鍵並移動到主屏幕時,鍵盤將保持打開狀態。

AlertDialogEditText顯示軟鍵盤的這個問題可能在AlertDialog.show() ,因為EditText在顯示AlertDialog后應用。 我不確定所有版本的 API 都是這種情況,但我認為該解決方案帶有 API 級別 21,因為它帶有AlertDialog.create() ,它應該在AlertDialog.show()之前AlertDialog.show()

這是我對這種情況的最佳解決方案。 首先,在某處創建:

    private int showKeyboard(View view) {
        final InputMethodManager inputManager = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            boolean isShown = inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // flag=InputMethodManager.SHOW_IMPLICIT ili =
            return (isShown) ? 1: -1;
        }
        return 0;
    }

然后,在您的AlertDialog.Builder builder = new AlertDialog.Builder(requireContext()); 繼續:

    EditText editText = new EditText(requireContext());
    builder.setView(editText);
    // ... put positive-negative buttons, and etc ...
    AlertDialog dialog = builder.create(); // Create dialog from builder
    dialog.setCancelable(false); // If you need
    Handler handler = new Handler();
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) { // 1. When a dialog is displayed
            editText.requestFocus();
            Runnable runnable = new Runnable() { // create one runnable
                int counter = 0;
                public void run() {
                    int status = showKeyboard(editText); // 2. Call func.above for keyboard, but...
                    if(status == -1 && counter < 10){ handler.postDelayed(this, 100); counter ++; } // ...if it inst shown call again after 100ms
                }
            };
            runnable.run(); // Execute runnable first time here
        }
    });
    dialog.show();

不要忘記import android.os.Handler; 等等。 ;-)

感謝Vote Up

我的方法使用 Android 11+ 的新方法,並且還支持舊版本:

fun Fragment.showKeyboard() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        ViewCompat.getWindowInsetsController(requireView())?.show(WindowInsetsCompat.Type.ime())
    } else {
        val focusedView = view?.findFocus() ?: view?.apply { requestFocus() }
        val imm = (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
        val isShowSucceeded = imm.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
        if(!isShowSucceeded) {
            imm.toggleSoftInputFromWindow(
                view?.windowToken, 0, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }
}

}

這對我有用。 我為對話框設置了一個 OnShowListener,在該偵聽器中,我為文本字段設置了一個 onFocusChangeListener,在該 FocusChangeListener 中,我以 100 毫秒的延遲調用 showSoftInput,然后刪除 FocusChangeListener,因此它僅處理第一個焦點更改。

調用dialog.show()時,會調用 OnShowListener,這會請求文本字段的焦點。 當文本字段獲得焦點時,將調用 FocusChangeListener 並最終顯示鍵盤。

    val views = DialogBinding.inflate(layoutInflater) // layout with 'textfield'
    val dialog = MaterialAlertDialogBuilder(requireContext())
        .setTitle("Exercise")
        .setView(views.root)
        ...
        .create()
    dialog.setOnShowListener {
        views.textfield.onFocusChangeListener = View.OnFocusChangeListener { view, _ ->
            view.postDelayed({
                (view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(view, 0)
            }, 100)                
            views.textfield.onFocusChangeListener = null
        }
        views.repcount.requestFocus()
    }
    dialog.show()

您可以在 EditText 上附加一個 onFocusListener 或在 AlertDialog 上附加一個 onShowListener 並添加以下內容:

val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)

edittext.setShowSoftInputOnFocus(true); 是關於問題主題的最流暢的解決方案。

AlertDialog.Builder alertSearch = new AlertDialog.Builder(activity);
alertSearch.setIcon(R.drawable.ic_launcher);
alertSearch.setTitle("Search");
final EditText edittext = new EditText(activity);
edittext.setSingleLine();
edittext.setHint("...");
edittext.setText(SearchString);

聚焦時設置鍵盤

edittext.setShowSoftInputOnFocus(true);

獲得焦點

edittext.requestFocus();

alertSearch.setView(edittext);
alertSearch.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // Do something
        act.recreate();
    }
});
alertSearch.show();

暫無
暫無

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

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