[Java] [Android 9.0 Pie Java] Implement setOnTouchListener in the margin of RecyclerView and close the soft keyboard

less than 1 minute read

at first

RecyclerView is convenient for displaying a list, but if you leave it as the default, you will not be able to fire an event when you touch the margin.
I sought an implementation to close the soft keyboard by touching the margin of RecyclerView, so I would like to share it.

32aeddc0c59703301a8fc30cf57374b6.gif

Implementation method

First to RecyclerView

android:touchscreenBlocksFocus="true"

Will be added.

fragment.xml


<LinearLayout
    android:id="@+id/scrollView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:isScrollContainer="false"
    app:layout_constraintBottom_toTopOf="@+id/footerBorder"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/headerBorder">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:touchscreenBlocksFocus="true"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</LinearLayout>

All you have to do now is implement the listener with onCreateView or onCreatedView.

Fragment.java


RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //Hide keyboard
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        //Move focus to background
        recyclerView.requestFocus();
        return false;
    }
});

that’s all.

I hope it will be helpful to anyone.