3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Android 9.0 Pie Java】RecyclerViewの余白部分にsetOnTouchListenerを実装してソフトキーボードを閉じる

Last updated at Posted at 2020-07-22

初めに

リスト表示に便利なRecyclerViewですが、デフォルトのままだと余白部分をタッチした際にイベントを発火させることができません。
RecyclerViewの余白部分をタッチしてソフトキーボードを閉じる為に実装を模索したので共有したいと思います。

32aeddc0c59703301a8fc30cf57374b6.gif

実装方法

まずRecyclerViewに

android:touchscreenBlocksFocus="true"

を追記します。

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>

あとはonCreateViewやonCreatedViewでリスナーを実装するだけです。

Fragment.java
RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // キーボードを隠す
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        // 背景にフォーカスを移す
        recyclerView.requestFocus();
        return false;
    }
});

以上です。

どなたかの参考になれたら幸いです。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?