背景
最近在開發(fā)項目中遇到一個問題,布局高度在小屏幕手機上高度不夠全部顯示,于是使用了ScrollView嵌套LinearLayout,但問題又出現(xiàn)了,LinearLayout設(shè)置了martch_parent屬性,但是卻顯示的并不是充滿全屏幕。
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff000">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
現(xiàn)象
探究
于是點進ScrollView的源碼里面尋找這個問題的答案,找到了這個方法。
/**
* Indicates whether this ScrollView's content is stretched to fill the viewport.
*
* @return True if the content fills the viewport, false otherwise.
*
* @attr ref android.R.styleable#ScrollView_fillViewport
*/
public boolean isFillViewport() {
return mFillViewport;
}
注釋上說這個方法的意思是是否ScrollView的內(nèi)容充滿視圖,true則充滿視圖,false則不是。看到這里,再往上找,發(fā)現(xiàn)這是這個字段對應(yīng)著一個屬性android:fillViewport
public ScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initScrollView();
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.ScrollView, defStyleAttr, defStyleRes);
setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false));
a.recycle();
}
到現(xiàn)在已經(jīng)很清晰了,把android:fillViewport="true" 屬性家進入試一下。問題解決,看效果圖。
最重要的是將ScrollView中android:fillViewport設(shè)置為true。
當(dāng)ScrollView里的元素想填滿ScrollView時,使用"fill_parent"是不管用的,必需為ScrollView設(shè)置:android:fillViewport="true"。
總結(jié)
當(dāng)ScrollView沒有fillVeewport=“true”時,里面的元素(比如LinearLayout)會按照wrap_content來計算(不論它是否設(shè)了"fill_parent"),而如果LinearLayout的元素設(shè)置了fill_parent,那么也是不管用的,因為LinearLayout依賴里面的元素,而里面的元素又依賴LinearLayout,這樣自相矛盾.所以里面元素設(shè)置了fill_parent,也會當(dāng)做wrap_content來計算.