在Android中隐藏键盘的最佳方式

sre*_*dev 5 keyboard android

我想知道在将文本输入EditText后隐藏键盘的最佳方法.

1)setonfocuschangelistener:当按下完成按钮或焦点从一个EditText变为另一个时,是否仅触发此侦听器?当我使用这种方法时,我无法隐藏键盘.

2)setOnTouchListener:当我使用它时,我可以隐藏键盘,但我怀疑这可能存在问题.在这种情况下,我将触摸侦听器添加到根LinearLayout.以下代码我用过:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    txtUserName = (EditText)findViewById(R.id.txtUserName);
    btnLogin = (Button)findViewById(R.id.btnLogin);
    layoutView = (LinearLayout)findViewById(R.id.li);

    layoutView.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(txtUserName
                    .getWindowToken(), 0);
            return true;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

在主要的LinearLayout中,我正在使用其他两个LinearLayouts.我面对上述代码的问题是,在我按下的某些时刻,键盘不会隐藏.我的疑问是我只使用root布局添加触摸侦听器,而不是给其他内部布局或其他控件(TextView)提供触摸侦听器.当我触摸其他控件或TextView周围的某些点(即内部布局)时,键盘不会隐藏.

这意味着我需要将touchListener添加到根布局内的所有布局或控件吗?如何以更好的方式处理这种情况?

Was*_*han 14

您可以使用此代码

InputMethodManager imm = 
    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditView.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)

  • 如果没有显示键盘,这将导致空指针异常.请添加一个修复程序 (3认同)

Hir*_*tel 9

我对这个问题的回答是:

添加此方法:

public static void hideSoftKeyboard(Activity activity) {
  InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
  inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
Run Code Online (Sandbox Code Playgroud)

如果您想在触摸屏时隐藏键盘,可以这样做:

@Override
public boolean onTouchEvent(MotionEvent event) {
 hideSoftKeyboard(LoginActivity.this);
 return false;
}
Run Code Online (Sandbox Code Playgroud)

希望这会帮助你.


Ron*_*hta 5

试试这个 :

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Run Code Online (Sandbox Code Playgroud)

它可用于抑制键盘,直到用户实际触摸edittext视图.

要么

 inputManager.hideSoftInputFromWindow(editView.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)