Reyhaneh SH Reyhaneh SH - 28 days ago 14
Android Question

How to hide keyboard just by one tap outside of an edittext?

I want to hide keyboard by tapping outside of edittext. This is my xml code:

<RelativeLayout
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:onClick="rl_main_onClick">
<RelativeLayout
//Here there are some widgets including some edittext.
</RelativeLayout>


This is my java code (MainActivity):

public void rl_main_onClick(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}


But I have to tap twice to hide keyboard. The first tap just changes "next" (for last edittext it's "done") to enter icon, then the second tap hides the keyboard.
This is what that happen by the first tap:

What the first tap does.

Now I have two questions:

1- How can I fix it and hide keyboard by just one tap?

2- Is it possible to do it for all of my edittext (one code for all)?

Thanks in advance.

Answer

Try to replace onClick with onTouch. For this you need to change your layout attributes like this:

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <RelativeLayout>
        //Here there are some widgets including some edittext.
    </RelativeLayout>

</RelativeLayout>

Then remove rl_main_onClick(View view) {...} method and insert onTouch listener method inside of onCreate() :

findViewById(R.id.relativeLayout).setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }
});
Comments