隐藏以在 DialogFragment 中显示和隐藏键盘

Hide to show and hide keyboard in DialogFragment

在我的对话框片段中,我可以使用

显示键盘
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);

两者都不起作用。

我还尝试使用

显示和隐藏键盘
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);
        }
    }

注意:我已阅读这些 Whosebug 帖子并尝试了建议的解决方案但无济于事:

  1. How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event
  2. Close/hide the Android Soft Keyboard

要隐藏键盘,请使用:

 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) {
        }
}

解决方案结果是以下组合。在 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);
    }

在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);

也许可以。

在 DialogFragment 内的视图中隐藏键盘:

public static void hideKeyboardInAndroidFragment(View view){
        final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

我有片段的扩展名,但没有使用对话框片段。此扩展适用于两者(没有经过太多测试)

/**
 * 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

编辑:切换打开的键盘,如果它之前是关闭的,我使用反射来获取键盘的高度,这不是最佳解决方案,但有效

隐藏软键盘可以使用这个方法:

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);
        }
    }

Kotil Extension function for DialogFragment hide keyboard

 use : hideKeyboard(view)
fun DialogFragment.hideKeyboard(view: View) {
    val imm =view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 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)
}