我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
public void hideKeyboard()
{
if(getCurrentFocus()!=null)
{
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
public void showKeyboard(View mView) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
mView.requestFocus();
inputMethodManager.showSoftInput(mView, 0);
}
其他回答
作为这一全面解决方案的替代方案,如果您想从任何地方关闭软键盘,而没有对用于打开键盘的(EditText)字段的引用,但仍然希望在该字段被聚焦时进行此操作,则可以使用(从“活动”):
if (getCurrentFocus() != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
如果您需要在片段中隐藏键盘,则此方法有效。
public static void hideSoftKeyboard(Context context, View view) {
if (context != null && view != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
对于视图,只需传入
getView() method
我已经尝试了所有的解决方案,但没有一个解决方案适合我,所以我找到了我的解决方案:您应该有如下布尔变量:
public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
在触摸屏事件中,您可以拨打:
@Override
public boolean onTouchEvent(MotionEvent event) {
if(keyboardShowing==true){
inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
keyboardShowing = false;
}
return super.onTouchEvent(event);
}
在EditText中的任何位置:
yourEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
yourClass.keyboardShowing = true;
}
});
首先,您应该从XML文件中添加addandroid:imeOptions字段,并将其值更改为actionUnspecified|actionGo,如下所示
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text_id"
android:layout_width="fill_parent"
android:layout_height="@dimen/edit_text_height"
android:imeOptions="actionUnspecified|actionGo"
/>
然后在java类中添加setOnEditorActionListener并添加InputMethodManager,如下所示
enterOrderNumber.setOnEditorActionListener(新的TextView.OnEditorActionlister(){
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
return true;
}
return false;
}
});
要在应用程序启动时显示键盘:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
view.requestFocus();
new Handler().postDelayed(new Runnable() {
public void run() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
}, 1000);