简体   繁体   English

按下按钮时清除编辑文本焦点并隐藏键盘

[英]Clear edittext focus and hide keyboard when button is pressed

I'm making an app with edittext and a button.我正在制作一个带有编辑文本和按钮的应用程序。 When I enter something into edittext and then click a button, I want the keyboard and focus on edittext to disappear but I can't seem to do it.当我在edittext 中输入一些内容然后单击一个按钮时,我希望键盘和edittext 上的焦点消失,但我似乎无法做到。

I inserted these 2 lines of code in XML:我在 XML 中插入了这两行代码:

android:focusable="true"
android:focusableInTouchMode="true"

I also tried to add this in the button click method:我还尝试在按钮单击方法中添加它:

edittext.clearFocus();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

And it just won't work, after I press the button, the keyboard remains there and edittext still has focus.它只是不起作用,在我按下按钮后,键盘保持在那里并且 edittext 仍然具有焦点。

To hide the keyboard call this:要隐藏键盘,请调用:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);

You can also check this solution: https://stackoverflow.com/a/15587937/786337您还可以查看此解决方案: https : //stackoverflow.com/a/15587937/786337

another solution is, create a dummy layout另一个解决方案是,创建一个虚拟布局

<!-- 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" />

and set the focus in your onButtonClickFunction并在您的onButtonClickFunction设置焦点

((LinearLayout) findViewById(R.id.dummy_id)).requestFocus();
InputMethodManager inputManager = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                     InputMethodManager.HIDE_NOT_ALWAYS);
editText.setText("");

Add the following on your button onclick event在您的按钮 onclick 事件中添加以下内容

You need to import android.view.inputmethod.InputMethodManager ;您需要import android.view.inputmethod.InputMethodManager

The keyboard hides and clears the text when you click the button.单击按钮时,键盘会隐藏和清除文本。

First you must disable the keyboard:首先,您必须禁用键盘:

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); }

Second clear view (Layout, EditText...)focus:第二个清晰的视图(布局、编辑文本...)焦点:

view.clearFocus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM