在網上看了很多關于如何解決RecyclerView 的item填充螢幕的文章,但是看到的那些文章幾乎方法都一樣,還是無法解決到我的問題。但是看了那麼多文章之後終于從一篇文章中找到了靈感,位址是:RecyclerView Item 布局寬高無效問題探究。這篇文章中探讨了為什麼item無法填充螢幕的原因。非常感謝這位作者!
廢話我就不多說 ,進入正題。我們獲得一個布局的時候 無非就是用inflate方法,這個 方法有四個重載方法,一般來說我用的比較多的就是.inflate(R.layout.xx, parent, false);和.inflate(R.layout.xx,null)這兩個方法,當我遇到item無法填充螢幕寬度的時候正是使用了第二個方法,于是我測試了第一個方法,解決了問題。通常我在使用Recycler View時,Item布局出問題,我就把兩個方法都試過(前提是布局沒問題),一般都可以解決掉,但是今天我要給RecyclerView添加一個HeaderView的時候,出現了HeaderView無法填充螢幕寬度的情況。我隻能使用上面提到的方法中的第二種方法,因為我不知道怎麼拿到父容器(我是菜鳥),具體代碼如下
public void setFooterView(int resId) {
this.headerView=LayoutInflater.from(mContext).inflate(resId,null);
notifyItemInserted();
}
在這個時候我也沒辦法解決,我也很絕望,是以我不停的去網上看文章,後來看到了前面提到的那篇文章,才知道,假如使用.inflate(R.layout.xx,null)加載布局,沒有父容器,得到的布局的寬高都是wrap_content的(不清楚的同學可以點連結進去看原因)。是以我在xml檔案中怎麼寫寬度和高度都是無效的。于是我想到了一個很爛的辦法解決這個問題。辦法如下:
解決問題的代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/grey"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/middle_margin"
android:layout_marginTop="@dimen/small_marginII"
android:text="熱門城市"
android:textColor="@color/black"
android:textSize="@dimen/bigII_text_size" />
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_hotCity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/middle_margin"
android:layout_marginRight="@dimen/middle_margin"
android:layout_marginTop="@dimen/small_marginII">
</android.support.v7.widget.RecyclerView>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginBottom="@dimen/small_margin"
android:layout_marginTop="@dimen/small_margin"
android:background="@color/textgrey" />
</LinearLayout>
這段代碼中大家可以看到末尾處有一個View,解決問題的關鍵就在這個View上面。我的想法是:既然你不管怎麼樣都是wrap_content,那麼我就把你撐到match_parent,于是我将View的寬度設定成match_parent,再次運作,發現我的headerview可以填充了。至此解決了我的問題。可能有人有疑惑為何我上面的textView是match_parent為何無法填充,具體我也不是很清楚,但是我覺得應該是它隻測量字型所占寬度,才會導緻這樣的效果吧。這是我目前知道的辦法,大神勿噴,如果誰有更好的辦法希望能告知一下,不勝感激。