Fry in the Web

次からこうしようと思ったことを書き残しておきます

RecyclerView、ListViewがずれる問題

Android でRecyclerViewを使う場合、最初のデータをaddAllしたあとnotifyItemChangedすることが多いと思いますが

RecyclerViewのItem内のViewがForcusableである場合

フォーカスが途中のItemに当たって何もしてないのに4番目のViewが一番上になって表示されたりします。

解決法はItemのレイアウトのルートにdescendantFocusabilityを設定することです。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:background="?android:attr/selectableItemBackground"
    android:descendantFocusability="blocksDescendants"
    android:layout_height="wrap_content">
</LinearLayout>

これでフォーカスを奪われること無くItemを表示できます。

ちなみに android:background="?android:attr/selectableItemBackground"を設定すると、

Rippleが表示されて少し見栄えが良くなります。


記事がだいぶ消えてしまって絶望してます