70

When my fragment starts, I want my edittext to be in focus/let user to just start typing in it. I am able to get it in focus with requestFocus(), but I cannot get the keyboard to show up.

I have tried both this:

edit = (EditText) view.findViewById(R.id.search);
edit.requestFocus();
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);

and

edit = (EditText) view.findViewById(R.id.search);
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);
edit.requestFocus();

How can I get the keyboard to show up for EditText?

4

13 回答 13

107

这行得通吗?

imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
于 2012-05-09T00:44:41.343 回答
18

你可以试试这个

@Override
public void onResume() {
    super.onResume();
    edit.post(new Runnable() {
        @Override
        public void run() {
            edit.requestFocus();
            InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imgr.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
        }
    });
}
于 2015-08-24T08:27:14.490 回答
15

由于 usingshowSoftInput不适用于所有情况,并且在尝试了此处提到的一些解决方案之后,例如:

if (binding.account.requestFocus()) {
  requireActivity().getWindow()
      .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}

我终于使它工作使用

if (binding.account.requestFocus()) {
  ((InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(
      InputMethodManager.SHOW_FORCED,
      InputMethodManager.HIDE_IMPLICIT_ONLY
  );
}

自从:

 binding.account.requestFocus()

只请求焦点EditText(它不打开键盘)

((InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(
      InputMethodManager.SHOW_FORCED,
      InputMethodManager.HIDE_IMPLICIT_ONLY
  );

是唯一似乎可以正常工作以显示键盘的解决方案(也是投票最多的解决方案)

祝你好运!:-)

于 2017-05-10T23:40:15.307 回答
10

我对此有帮助的扩展:

fun EditText.showKeyboard() {
    if (requestFocus()) {
        (getActivity()?.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
            .showSoftInput(this, SHOW_IMPLICIT)
        setSelection(text.length)
    }
}

你还需要这个:

fun View.getActivity(): AppCompatActivity?{
    var context = this.context
    while (context is ContextWrapper) {
        if (context is AppCompatActivity) {
            return context
        }
        context = context.baseContext
    }
    return null
}
于 2018-10-16T09:19:45.080 回答
5

在尝试了此处的所有解决方案以及其他相关问题之后,以下是适用于我的方法:

editText.postDelayed(Runnable { showKeyboard(activity, editText)} , 50)


fun showKeyboard(activity: Activity, editText: EditText) {
    val inputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    editText.requestFocus()
    inputMethodManager.showSoftInput(this, 0)
}

有趣的事实是,当你在没有 postDelayed 的情况下调用它时,它不会工作,即使你只是将它延迟 1 毫秒,它仍然不会工作:D

你也可以像这样使用它作为扩展:

fun EditText.showKeyboard(activity: Activity) {
    val inputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    requestFocus()
    inputMethodManager.showSoftInput(this, 0)
}

如果您不喜欢将活动作为参数传递,请按照@Rafols 的建议使用此扩展功能:

fun View.getActivity(): AppCompatActivity? {
    var context = this.context
    while (context is ContextWrapper) {
        if (context is AppCompatActivity) {
            return context
        }
        context = context.baseContext
    }
    return null
}

那么您的方法将如下所示:

fun EditText.showKeyboard() {
    val inputMethodManager = getActivity()!!.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    requestFocus()
    inputMethodManager.showSoftInput(this, 0)
}

此外,如果您的 EditText 中已有文本,则在现有文本的末尾设置更好的选择:

fun EditText.showKeyboard() {
    val inputMethodManager = getActivity()!!.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    requestFocus()
    inputMethodManager.showSoftInput(this, 0)
    setSelection(length())
}

如果你想在片段开始时启动它:

override fun onResume() {
    super.onResume()
    editText.postDelayed(Runnable { editText.showKeyboard()} , 50)
}
于 2019-05-14T13:52:48.800 回答
4
    @Override
public void onHiddenChanged (boolean hidden)
{
    super.onHiddenChanged(hidden);

    if(hidden)
    {
        hideKeyboard(yourView);
    }
    else
    {
        toggleKeyboard(yourView);
    }
}

    public static void toggleKeyboard(View v)
{
    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    v.requestFocus();

    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);
}

public static void hideKeyboard(View v)
{
    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
于 2016-05-31T12:39:44.473 回答
2

编辑文本。requestFocus () + 输入法管理器。showSoftInput () = 为 EditText 显示 IME

使用编辑文本。在Fragment.onViewCreated () 中执行AccessibilityAction (AccessibilityNodeInfo.ACTION_CLICK, null)

    void maybeShowInputMethod() {
        // use addOnPreDrawListener instead of addOnGlobalLayoutListener
        // because execute sequence: onGlobalLayout-> Restore focus -> onPreDraw
        getView().getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                // TODO Auto-generated method stub
                getView().getViewTreeObserver().removeOnPreDrawListener(this);

                // always requestFocus when fragment enter or show
                getView().requestFocus();
                final View currentFocus = getView().findFocus();
                if ((currentFocus != null) && currentFocus.onCheckIsTextEditor()) {
                    Log.d(TAG, "maybeShowInputMethod:: currentFocus=" + currentFocus);
                    currentFocus.performAccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, null);
                }
                return true;
            }
        });
    }

或创建 EditText 的子类并覆盖public InputConnection onCreateInputConnection(EditorInfo editorInfo)

public class ImeAwareEditText extends EditText {
private boolean mHasPendingShowSoftInputRequest;
final Runnable mRunShowSoftInputIfNecessary = () -> showSoftInputIfNecessary();

public ImeAwareEditText(Context context) {
    super(context, null);
}

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

public ImeAwareEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public ImeAwareEditText(Context context, AttributeSet attrs, int defStyleAttr,
        int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

/**
 * This method is called back by the system when the system is about to establish a connection
 * to the current input method.
 *
 * <p>This is a good and reliable signal to schedule a pending task to call
                                                                                                                                                                                                                     52,6          Top
 *
 * <p>This is a good and reliable signal to schedule a pending task to call
 * {@link InputMethodManager#showSoftInput(View, int)}.</p>
 *
 * @param editorInfo context about the text input field.
 * @return {@link InputConnection} to be passed to the input method.
 */
@Override
public InputConnection onCreateInputConnection(EditorInfo editorInfo) {
    final InputConnection ic = super.onCreateInputConnection(editorInfo);
    if (mHasPendingShowSoftInputRequest) {
        removeCallbacks(mRunShowSoftInputIfNecessary);
        post(mRunShowSoftInputIfNecessary);
    }
    return ic;
}

private void showSoftInputIfNecessary() {
    if (mHasPendingShowSoftInputRequest) {
        final InputMethodManager imm =
                getContext().getSystemService(InputMethodManager.class);
        imm.showSoftInput(this, 0);
        mHasPendingShowSoftInputRequest = false;
    }
}

public void scheduleShowSoftInput() {
    final InputMethodManager imm = getContext().getSystemService(InputMethodManager.class);
    if (imm.isActive(this)) {
        // This means that ImeAwareEditText is already connected to the IME.
        // InputMethodManager#showSoftInput() is guaranteed to pass client-side focus check.
        mHasPendingShowSoftInputRequest = false;
        removeCallbacks(mRunShowSoftInputIfNecessary);
        imm.showSoftInput(this, 0);
        return;
    }

    // Otherwise, InputMethodManager#showSoftInput() should be deferred after
    // onCreateInputConnection().
    mHasPendingShowSoftInputRequest = true;
}
}
于 2019-10-25T10:27:01.863 回答
1

科特林

要在片段中自动显示/隐藏键盘...

override fun onResume() {
    super.onResume()

    requireView().edit_text_ID.showKeyboard()

    requireView().edit_text_ID.setOnFocusChangeListener { _, hasFocus ->
     if (!hasFocus){
        hideKeyboardFrom(requireContext(), requireView())
     }
    }
}

fun EditText.showKeyboard() {
    if (requestFocus()) {
        (activity?.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
            .showSoftInput(this, SHOW_IMPLICIT)
        setSelection(text.length)
    }
}

fun hideKeyboardFrom(context: Context, view: View) {
    val imm =
        context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

这里有一点信息。

于 2020-05-21T23:12:37.767 回答
0

简单地说,使用添加 2 行就像一个魅力:

如果使用 XML

android:focusable="true"
android:focusableInTouchMode="true"

Java中的其他内容:

view.setFocusableInTouchMode(true);
view.requestFocus();
于 2017-07-05T10:25:01.103 回答
0

当片段启动时打开键盘的另一种方法是调用requestFocus()onCreateView通过打开键盘做出相应的反应,当且仅当它EditText是可聚焦的。

if(this.editText.requestFocus())
{
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
于 2016-04-25T21:47:59.853 回答
0

科特林

启动片段时键盘打开

    override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val fragmentView = inflater.inflate(R.layout.fragment_main, container, false)

    activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    return fragmentView
}
于 2020-08-04T15:30:24.053 回答
-1

正如 Nilzor 所说,这行得通

imgr.showSoftInput(getView(), InputMethodManager.SHOW_IMPLICIT)

我同意它是比 toogleSoftInput 最好的解决方案

于 2015-04-25T14:39:36.213 回答
-1

这篇文章帮助了我

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 
{
  View view = inflater.inflate(R.layout.fragment_edit_name, container);
  editText = (EditText) view.findViewById(R.id.txt_yourName);
  editText.requestFocus();
  getDialog().getWindow().setSoftInputMode(
                       LayoutParams.SOFT_INPUT_STATE_VISIBLE);
   return view;
}

https://turbomanage.wordpress.com/2012/05/02/show-soft-keyboard-automatically-when-edittext-receives-focus/

于 2017-03-20T13:43:36.860 回答