按下按钮时清除edittext焦点并隐藏键盘
问题描述:
我正在用edittext和一个按钮制作应用程序。当我在edittext中输入内容然后点击一个按钮时,我需要键盘并专注于edittext消失,但我似乎无法做到。按下按钮时清除edittext焦点并隐藏键盘
我插入这2行代码在XML:
android:focusable="true"
android:focusableInTouchMode="true"
我也试图在按钮点击方法补充一点:
edittext.clearFocus();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
它只是将无法正常工作后,我按下按钮,键盘保持在那里,edittext仍然有焦点。
答
另一种解决方案是,创建一个虚拟布局
<!-- 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();
答
隐藏键盘调用此:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
您还可以检查此解决方案: https://*.com/a/15587937/786337
+2
这是正确的答案 –
答
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
editText.setText("");
添加以下你的按钮onclick事件
您需要import android.view.inputmethod.InputMethodManager
;
当您单击按钮时,键盘将隐藏并清除文本。
对我不起作用 –