如果Android软键盘已打开,如何隐藏?

11

我有三个编辑文本字段。其中,我希望仅为第一个字段显示软输入键盘,并对后两个字段禁用,因为它们是日期和时间字段。

Edit-Text 1 //Show the keyboard
Edit-Text 2 and 3 //Hide the keyboard

使用以下代码,我能够禁用第二个和第三个字段的键盘,但当用户聚焦于第一个字段时,键盘出现但在用户点击第二个或第三个字段时没有隐藏。尽管当先点击第二个或第三个字段时不会弹出键盘。

//Code to disable soft input keyboard
public static void disableSoftInputFromAppearing(EditText editText) {
    if (Build.VERSION.SDK_INT >= 11) {
        editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
        editText.setTextIsSelectable(true);
    } else {
        editText.setRawInputType(InputType.TYPE_NULL);
        editText.setFocusable(true);
    }

如果软输入键盘已经打开,我该如何隐藏它?


Kotlin - https://dev59.com/fFgR5IYBdhLWcg3wEZyV#45857155 - ritwikshanker
4个回答

22

//活动

public static void hideSoftKeyboard(Activity activity) {

   InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
   inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
 }

// 片段

public void hideSoftKeyboard() {
    InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}

// 如果编辑文本失去焦点,隐藏键盘

edTxtMessage.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (isEditable){
                v.setFocusable(true);
                v.setFocusableInTouchMode(true);
            } else {
                edTxtMessage.setFocusable(false);
            }

            return false;
        }
    });

edTxtMessage.setOnFocusChangeListener(new View.OnFocusChangeListener({
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b){
                hideKeyboard(getContext(), view);
            }
        }
    });

private void hideKeyboard(Context context, View view) {
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

我正在片段上。 - Paras

0

检查当前焦点是否不为空,否则可能会导致空指针异常

if (getCurrentFocus() != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

0

简单的方法是使用 XML

android:inputType="none"
android:textIsSelectable="true

我已经尝试过了。如果我点击第一个字段,键盘就会出现,直到我按下向下按钮它才会消失。 - Paras

0

你可以将这两个属性设置到你的EditText上

  android:focusable="false"
  android:focusableInTouchMode="false"

注意:通过这种方式,您的EditText可以点击日期和时间,而不会聚焦到软键盘。

实际上,我正在on-focus事件上触发日期时间选择器,因为在on-click的情况下,在on-focus之后第二次调用它。 - Paras
我不明白。 - Arjun saini

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