Android
Soft Keyboard
EditText
UI Development
Mobile App Tips

How to hide soft keyboard on android after clicking outside EditText?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When developing Android applications, handling the soft keyboard behavior is a common task, particularly when dealing with EditText components. Users expect the keyboard to disappear after interaction with other UI elements. By default, the keyboard does not automatically hide when you tap outside an EditText. This article provides a thorough exploration of different techniques to hide the soft keyboard in an Android application when clicking outside an EditText.

Understanding the Soft Keyboard

In Android, the soft keyboard (or on-screen keyboard) is a virtual keyboard which can be displayed or hidden based on user interaction or programmatic control. Managing the visibility of the keyboard is crucial to ensure a seamless user experience.

Core Strategy to Hide Soft Keyboard

To hide the keyboard after clicking outside of an EditText, you can use one of the following approaches:

  1. Touch Listener on Root View: Detect touches on the root view and hide the keyboard when a touch is detected.
  2. Focus Change Listener on EditText: Listen for focus changes on the EditText and hide the keyboard when the EditText loses focus.
  3. Override Activity Touch Events: Override the dispatchTouchEvent method of the Activity to catch touch events.
  4. Custom View Extensions: Extend existing views with custom behavior for hiding the keyboard.

Touch Listener on Root View

One straightforward approach is to set a touch listener on the root view of your activity. Here is how you can implement that:

java
1public class MainActivity extends AppCompatActivity {
2    @Override
3    protected void onCreate(Bundle savedInstanceState) {
4        super.onCreate(savedInstanceState);
5        setContentView(R.layout.activity_main);
6
7        RelativeLayout rootView = findViewById(R.id.root_view);
8        rootView.setOnTouchListener((v, event) -> {
9            if (event.getAction() == MotionEvent.ACTION_DOWN) {
10                View focusedView = getCurrentFocus();
11                if (focusedView instanceof EditText) {
12                    hideKeyboard(focusedView);
13                }
14            }
15            return false;
16        });
17    }
18
19    private void hideKeyboard(View view) {
20        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
21        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
22    }
23}

Focus Change Listener on EditText

You can set a focus change listener directly on each EditText. When focus is lost, hide the keyboard:

java
1editText.setOnFocusChangeListener((v, hasFocus) -> {
2    if (!hasFocus) {
3        hideKeyboard(v);
4    }
5});

Override Activity Touch Events

By overriding the dispatchTouchEvent in your Activity, you gain control over all touch events, allowing you to conditionally hide the soft keyboard:

java
1@Override
2public boolean dispatchTouchEvent(MotionEvent ev) {
3    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
4        View view = getCurrentFocus();
5        if (view instanceof EditText) {
6            Rect outRect = new Rect();
7            view.getGlobalVisibleRect(outRect);
8            if (!outRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
9                hideKeyboard(view);
10            }
11        }
12    }
13    return super.dispatchTouchEvent(ev);
14}

Custom View Extensions

For a more reusable solution, consider creating custom views or utility methods that encapsulate the keyboard hiding logic.

Implementation Considerations

  • Usability: Ensure that hiding the keyboard does not obscure necessary interactions. Always consider the user's perspective.
  • Performance: Excessive use of listeners can impact performance. Structure your code efficiently.
  • Compatibility: Test across various devices and versions of Android to ensure consistent behavior.

Summary Table

MethodDescriptionProsCons
Touch Listener on RootSet touch listener to detect taps outside EditTextSimple to implementMay interfere with other touch events
Focus Change ListenerHide keyboard when EditText loses focusDirect focus-based controlNeeds to be set for each EditText
Override Touch EventsArray all events at Activity levelCentralized control over touch eventsCan be complex for beginners
Custom View ExtensionsEncapsulate behavior within custom componentsHighly reusable and modularRequires additional setup and code

Additional Tips

  • Soft Input Mode: Use the windowSoftInputMode attribute in your AndroidManifest.xml to control default behavior, such as pan or resize for the activity.
xml
1  <activity
2      android:name=".MainActivity"
3      android:windowSoftInputMode="adjustResize">
4  </activity>
  • Keyboard Visibility: This can be manually controlled using InputMethodManager.showSoftInput or InputMethodManager.hideSoftInputFromWindow.

Managing keyboard visibility in Android applications enhances usability significantly and is an essential skill for Android developers to master. While there are multiple techniques to hide the keyboard when an EditText loses focus, choosing the right one depends on your application's architecture and specific user experience requirements.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.