【Android】RecyclerViewセル内のlayout_weightが効かない時の対処方法
今後もハマりそうなので備忘録。
事象
RecyclerViewのセル内でlayout_weightを使用したView表示しても、layout_weightが効かない場合がある。 スクロールしてセルが再度読み込まれた時にやっと効く。
画面のレイアウト
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.RecyclerView android:id="@+id/tagRecyclerView" android:layout_width="match_parent" android:layout_height="300dp" /> </LinearLayout>
セルのレイアウト
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="10dp" android:orientation="horizontal" android:padding="5dp"> <ImageView android:id="@+id/tagImg" android:layout_width="wrap_content" android:layout_height="match_parent" android:src="@drawable/ic_tag" /> <TextView android:id="@+id/tagNm" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:gravity="start|center" android:layout_weight="1" android:text="tagNm" android:textSize="16sp" /> <CheckBox android:id="@+id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" /> </LinearLayout>
解決方法
結論、RecyclerViewを覆うLayoutを「LinearLayout」から「RelativeLayout」にすることで解決。
色々調べたら、同様の事象を質問している方がいた。
LinearLayoutをRelativeLayoutに変更
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.RecyclerView android:id="@+id/tagRecyclerView" android:layout_width="match_parent" android:layout_height="300dp" /> </LinearLayout>
から
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.RecyclerView android:id="@+id/tagRecyclerView" android:layout_width="match_parent" android:layout_height="300dp" /> </RelativeLayout>
に変更
以上です