How to close/hide the Android soft keyboard programmatically?
#1
I'm working on an Android app where I have a UI that contains an EditText and Button. My goal is to have the virtual keyboard hide automatically when I click the button after entering some text in the EditText. I've tried a few different methods, but none of them seem to work properly for me. Does anyone have a reliable approach for accomplishing this? I'm looking for a straightforward way that doesn't involve overly complex code.
Here's a snippet of my layout XML file, but I'm unsure how to proceed with the Java part for hiding the keyboard:

Code:
xml
    <
    RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android: layout_width = "match_parent"
android: layout_height = "match_parent" >
    <
    EditText
android: id = "@+id/editText"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: hint = "Type here..." / >
    <
    Button
android: id = "@+id/button"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_below = "@id/editText"
android: text = "Submit" / >
    <
    /RelativeLayout>

Can someone point me in the right direction for the Java code needed to hide the keyboard when the button is clicked?
Reply
#2
Hiding the keyboard involves accessing the InputMethodManager and requesting it to hide the soft input window. Below is a method you can call within the onClickListener of your button:

Code:
}
}

To use this method, you'll want to set an onClickListener for your button in your activity's onCreate method. Here's an example using a lambda expression (assuming your Activity is named MainActivity):

Code:
public class MainActivity extends AppCompatActivity {
    private EditText editText;
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);
        button.setOnClickListener(this::hideKeyboard);
    }
    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

Ensure you call this hideKeyboard method within the context of an Activity, because getSystemService is a method that's part of the Activity class. If you place hideKeyboard in a non-Activity class, you will need to pass a Context to it.
Reply
#3
I've implemented your suggestion, but it seems the keyboard only hides if I specifically touch the button, not when touching outside of the keyboard. Am I missing something here? My users may expect to be able to touch anywhere outside the keyboard to dismiss it.
Reply
#4
Ah, I see. To dismiss the keyboard when touching outside, you can override the dispatchTouchEvent method in your Activity to detect touches outside the EditText and then hide the keyboard accordingly:

Code:
public class MainActivity extends AppCompatActivity {
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.editText);
        // The rest of your onCreate code...
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    v.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }
}

Remember to import the necessary classes, such as Rect and View. With this code, whenever there's a touch event dispatched to the activity, it checks if the current focus is an instance of EditText and then if the touch is outside of it. If these conditions are true, the keyboard will hide.
Reply
#5
That seems to meet the requirements, and it's working as expected now when I added your dispatchTouchEvent method. Thanks for the assistance.
Reply
#6
No problem. Make sure to test on different screen sizes and orientations to ensure consistent behavior across various devices.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)