隐藏Android软键盘(如果已打开)

问题描述 投票:4回答:3

我有三个编辑文本字段。在这些字段中,我想仅显示第一个字段的软输入键盘,而后两个字段禁用这些字段,这些是日期和时间字段。

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

通过使用下面的代码,我可以禁用字段2和3的键盘,但是当用户将焦点放在字段1上时,键盘会出现,但是当用户点击字段2或3时,键盘不会隐藏。尽管字段2或3是首先敲击没有键盘出现。

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

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

android keyboard
3个回答
13
投票

//活动

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

0
投票

简单的方法是使用xml

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

0
投票

您可以将两个属性设置为edittext

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

注意:通过这个您的edittext可以点击日期和时间不关注软键盘

© www.soinside.com 2019 - 2024. All rights reserved.