Reason analysis and solution of failure to retract input board caused by EditText+Button combination in Android

  • 2021-01-06 00:44:26
  • OfStack

Entering information is the most basic operation in Android development and is widely used.

However, Android's support for input method pop-up/fallback is not very good.

force and implicit are provided for pop-ups, but force is not provided for input.

Can imagine, want to play can play, want to receive can not receive, this is how painful!

Without any processing on the input method, EditText input, click Button1 will automatically put away the input method.

If it is not folded, there may be a problem with the layout. Try adding scrollView to the outermost layer.

The authors have personally tested that nesting scrollView works in most cases.

If the above method still fails to solve the problem, and you are very persistent in the automatic retraction of the input board (unfortunately, PM1 is usually so persistent), you can consider the following method

Modifications to EditText

Overwrite the onFocusChange method of EditText by adding the following code


InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (!hasFocus) {
manager.hideSoftInputFromWindow(getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} else {
manager.showSoftInput(this, );
} 

This code ensures that ES45en will pop up the input method when it gains focus, and close the input method when it loses focus.

Modifications to Button

The following method is called in the onClick method and the business process is done after the call


public static void obtainFocus(View v) {
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setFocusableInTouchMode(false);
}

Through the above two ends of the code, click Button after the input board can be normally retracted.

But when you enter the page and the input pad pops up, you have to deal with that separately.

The principle of

EditText part

By monitoring the change of focus, display and hide the input board.

The change in focus can be monitored by the View. onFucusChange method.

Button part

When ES85en is clicked, focus is first obtained before business processing.

Click on the event to register via View.onClickListener.

You may have some doubts about setFocusableInTouchMode call twice, is actually called twice in order to be able to perform multiple requestFocus method (requestFocus method need focusableInTouchMode true).

In the case where FocusableInTouchMode is true, the first click on Button will bring Button into focus, and the next click will bring onClick back.

In order to ensure that onClick can be called back with each click, we first set focusableInTouchMode to true, so that requestFocus can be called for focus acquisition, then set focusableInTouchMode to false to ensure that onClick can still correspond to onClick normally the next time we click.


Related articles: