在DialogFragment中隐藏和显示键盘

14

在我的对话框片段中,我可以使用以下方式显示键盘:

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);

但我无法在dismiss上隐藏它。

我已经尝试过

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

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

两个都不起作用。

我还尝试了使用


</p><input type="text" autofocus=""><p>显示和隐藏键盘。

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

并且

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

但是这些无法显示或隐藏键盘。

 public static class MyDialogFragment extends DialogFragment
    {
        @Nullable @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            return inflater.inflate(R.layout.my_input_dialog, container, false);
        }

        @Override
        public void onViewCreated(View v, Bundle savedInstanceState)
        {
            super.onViewCreated(v, savedInstanceState);

            final EditText editText = (EditText)v.findViewById(R.id.input);
            // this line below is able to show the keyboard 
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); 
            Button add = (Button)v.findViewById(R.id.add_btn);
            add.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    // other code not shown
                    dismiss();
                }
            });
            Button cancel = (Button)v.findViewById(R.id.cancel_btn);
            cancelButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    dismiss();
                }
            });
        }

        @Override
        public void onDismiss(DialogInterface dialog)
        {
            //this line below does NOT work, it does not hide the keyboard
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            super.onDismiss(dialog);
        }
    }

注意:我已阅读这些 stackoverflow 帖子,并尝试了提出的解决方案,但都没有成功:

  1. 如何在 DialogFragment 被 setCanceledOnTouchOutside 事件取消时隐藏屏幕键盘
  2. 关闭/隐藏 Android 软键盘
8个回答

35

解决方案是以下内容的组合。要在DialogFragment中显示键盘:

    @Override
    public void onResume()
    {
        super.onResume();
        editText.post(new Runnable()
        {
            @Override
            public void run()
            {
                editText.requestFocus();
                InputMethodManager imm =
                    (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null)
                    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
            }
        });
    }

要隐藏它,请使用@Shekhar上面提供的解决方案

    @Override
    public void onDismiss(DialogInterface dialog)
    {
        InputMethodManager imm =
            (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive())
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        super.onDismiss(dialog);
    }

1
终于!我缺少的是从EditText获取上下文。谢谢! - user1228891
有时候,当我快速显示和关闭对话框时,键盘仍然可见。有什么想法吗? - Berťák
将其放置在onDismiss中非常重要。例如,在onStop中它不起作用,无论如何。 - Dimitri Schultheis
有趣的是,如果不在“post {}”中调用,“imm.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT)”将无法正常工作。为什么呢? - iCantC

6
在DialogFragment中隐藏View内的键盘:
public static void hideKeyboardInAndroidFragment(View view){
        final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

4

使用以下代码隐藏键盘:

 private void hideKeyboard() {
        try {
            InputMethodManager inputManager = (InputMethodManager) _activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(_activity.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
}

谢谢,我已经点赞了,但这不是完整的答案。这只回答了问题的一部分(隐藏)。请注意,当使用getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);打开键盘时,此答案无法关闭键盘。请查看下面的答案以解决我的问题。 - VIN

2

如果想要隐藏软键盘,你可以使用以下方法:

原始答案:Original Answer

public void hideSoftKeyboard() {
        try {
            View windowToken = getDialog().getWindow().getDecorView().getRootView();
            InputMethodManager imm = (InputMethodManager) getDialog().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow( windowToken.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception ex) {
            Log.e(ex);
        }
    }

最终在DialogFragment中成功了,谢谢。 - Aleksadnre Bibilashvili

0

在 DialogFragment 的 onDestroyView() 方法中隐藏它:

 View view = getActivity().getCurrentFocus();
        if (view == null) view = new View(activity);
        InputMethodManager imm = (InputMethodManager)     getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

可能有效。


0

我有一个用于Fragment的扩展,但是在Dialog Fragment中无法使用。不过这个扩展应该可以同时适用于两者(尽管没有进行过太多测试)。

/**
 * If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
 *
 * @param useReflection - whether to use reflection in case of no window token or not
 */
fun Fragment.hideKeyboard(context: Context = App.instance, useReflection: Boolean = true) {
    val windowToken = view?.rootView?.windowToken
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    windowToken?.let {
        imm.hideSoftInputFromWindow(windowToken, 0)
    } ?: run {
        if (useReflection) {
            try {
                if (getKeyboardHeight(imm) > 0) {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            } catch (exception: Exception) {
                Timber.e(exception)
            }
        }
    }
}

fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int

编辑:如果之前关闭了键盘,则切换打开键盘。我使用反射来获取键盘的高度,这不是最佳解决方案,但可以工作。


0

如果你想在对话框显示时显示键盘,并在对话框消失时隐藏键盘,我只发现了一种完全可行的方法。

<style name="InputDialog" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="android:windowSoftInputMode">stateAlwaysVisible</item>
</style>

然后你应该在DialogFragment中使用上面的主题

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NORMAL, R.style.InputDialog)
}

-1
Kotil扩展函数用于DialogFragment隐藏键盘。
 use : hideKeyboard(view)
fun DialogFragment.hideKeyboard(view: View) {
    val imm =view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接