我想知道在将文本输入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;
}
});
}
在主要的LinearLayout中,我正在使用其他两个LinearLayouts。我面对上述代码的问题是,在我按下的某些时刻,键盘不会隐藏。 我的疑问是我只使用root布局添加触摸侦听器,而不是给其他内部布局或其他控件(TextView)提供触摸侦听器。当我触摸其他控件或TextView周围的某些点(即内部布局)时,键盘不会隐藏。
这意味着我需要将touchListener添加到根布局内的所有布局或控件吗? 如何以更好的方式处理这种情况?
答案 0 :(得分:14)
您可以使用此代码
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditView.getWindowToken(), 0);
答案 1 :(得分:9)
我对这个问题的回答:
添加此方法:
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
如果您想在触摸屏时隐藏键盘,可以这样做:
@Override
public boolean onTouchEvent(MotionEvent event) {
hideSoftKeyboard(LoginActivity.this);
return false;
}
希望这会对你有所帮助。
答案 2 :(得分:5)
试试这个:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
在用户实际触摸edittext视图之前,它可用于抑制键盘。
或
inputManager.hideSoftInputFromWindow(editView.getWindowToken(), 0);
答案 3 :(得分:2)
如果没有关注视图,只需检查 null 或 try-catch 即可避免使用NullPointerException
。
public void hideKeyboard(Activity activity) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null) {
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
答案 4 :(得分:-1)
隐藏键盘的最佳方法,只需在您的活动中dispatchDoneKey
。如果键盘处于可见状态,它将被隐藏。
public void dispatchDoneKey() {
dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}