hlbak
hlbak

Reputation: 27

onFocusChange called multiple times results in "hasFocus" variable to be unusable

I have two EditText widgets and want to hide the keyboard when the user clicks outside of those (if the keyboard is still active at that time obviously). To do this I am using a setOnFocusChangeListener on both of them like so :

eTNom=convertView.findViewById(R.id.EditText_nom);

eTNom.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) 
            hideKeyboard(v);
    }
});

The other setOnFocusChangeListener is handled exactly the same way.

However this does not work because the onFocusChange method is called multiple times (4-5) every time I click on one of the two EditText. This results in the hasFocus variable switching between true and false rapidly after the method is called and the keyboard only shows up for a very brief moment.

Here's exactly what's happening : https://i.sstatic.net/uGy1C.jpg

I have seen this question asked once but the accepted answer suggested to add android:windowSoftInputMode="adjustPan" in the manifest file. I did that but it did not solve my problem. I also saw people recommending to set the clickable, focusable and focusableInTouchMode attributes to true in the parent layout, which I also did, but it still does not work.

I thought that the problem came from the fact that I have two EditText widgets but when I deleted one from my activity I still had the same problem so I am pretty much lost right now and any sort of help would be really appreciated.

Thanks.

Upvotes: 1

Views: 1213

Answers (2)

Arwy Shelke
Arwy Shelke

Reputation: 350

Put below lines in Menifest

<activity android:name=".ActivityName"
      android:windowSoftInputMode="stateHidden"  />

OR you can show/hide the keyboard by using below two functions

public void hideSoftKeyboard() {
    if(getCurrentFocus()!=null) {
       InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
       inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

 /* Shows the soft keyboard */
public void showSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    view.requestFocus();
    inputMethodManager.showSoftInput(view, 0);

}

Upvotes: 2

Sultan Mahmud
Sultan Mahmud

Reputation: 1285

Apply this way:

etTextInput.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus) {
                    etTextInput.removeTextChangedListener(textWatcher);
                    etTextInput.addTextChangedListener(textWatcher);
                } else {
                    etTextInput.removeTextChangedListener(textWatcher);
                }
            });

Upvotes: 0

Related Questions