我正在制作带有edittext和按钮的应用。当我在edittext中输入内容然后单击一个按钮时,我想要键盘并专注于edittext消失,但我似乎无法做到。
我在XML中插入了这两行代码:
android:focusable="true"
android:focusableInTouchMode="true"
我还尝试在按钮点击方法中添加它:
edittext.clearFocus();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
它只是不起作用,按下按钮后,键盘仍然在那里,edittext仍然有焦点。
答案 0 :(得分:12)
要隐藏键盘,请拨打以下电话:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
您还可以查看此解决方案: https://stackoverflow.com/a/15587937/786337
答案 1 :(得分:12)
另一个解决方案是,创建一个虚拟布局
<!-- Dummy item for focus at startup -->
<LinearLayout
android:id="@+id/dummy_id"
android:orientation="vertical"
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
并将焦点设置在onButtonClickFunction
((LinearLayout) findViewById(R.id.dummy_id)).requestFocus();
答案 2 :(得分:1)
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
editText.setText("");
在按钮onclick事件
上添加以下内容您需要import android.view.inputmethod.InputMethodManager
;
单击按钮时,键盘会隐藏和清除文本。
答案 3 :(得分:0)
首先,您必须禁用键盘:
void hideKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager manager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert manager != null && view != null;
manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
第二个清晰的视图(布局,EditText ...)焦点:
view.clearFocus