Search code examples
androidandroid-edittextandroid-softkeyboardback-button

Android : Handle back button click when keyboard is open for EditText


When I am writing something in EdiText and pressing the back button, it is hiding the keyboard, which is perfect. But I want to handle this Back Button Click when Keyboard is open for EditText. The reason is I want to clear EditText's text when the back button is pressed when the keyboard is open.

Activity method onBackPressed() is not called when keyboard is open for EditText.

I checked here but didn't help though.

Any help would be appreciated.


Solution

  • I did few modifications to @GuanHongHuang's answer and now I am able to do this by these 3 steps:

    1. Creating Custom EditText Class to handle Back Press:

    public class CustomEditTextWithBackPressEvent extends androidx.appcompat.widget.AppCompatEditText {
    
    private MyEditTextListener onBackPressListener;
    
    public CustomEditTextWithBackPressEvent(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public void setOnBackPressListener(MyEditTextListener onBackPressListener) {
        this.onBackPressListener = onBackPressListener;
    }
    
    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                event.getAction() == KeyEvent.ACTION_UP) {
            //back button pressed
            if (Objects.requireNonNull(ViewCompat.getRootWindowInsets(getRootView())).isVisible(WindowInsetsCompat.Type.ime())) {
                //keyboard is open
                onBackPressListener.callback();
            }
            return false;
        }
        return super.dispatchKeyEvent(event);
    }
    
    public interface MyEditTextListener {
        void callback();
    }
    

    }

    2. Replace your normal EditText with this CustomEditTextWithBackPressEvent in XML

    <CustomEditTextWithBackPressEvent
        android:id="@+id/etSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/search_hint"
        android:imeOptions="actionSearch"
        android:inputType="text"
        android:maxLines="1" />
    

    3. Handle Back Press:

    binding.etSearch.setOnBackPressListener(() -> {
            //handle click
            //your code here
        });