使用ScrollView屬性fillViewport解決android布局不能撐滿全屏的問題

背景

最近在開發項目中遇到一個問題,布局高度在小屏幕手機上高度不夠全部顯示,于是使用了ScrollView嵌套LinearLayout,但問題又出現了,LinearLayout設置了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>

現象

image

探究

于是點進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的內容充滿視圖,true則充滿視圖,false則不是。看到這里,再往上找,發現這是這個字段對應著一個屬性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();
    }

到現在已經很清晰了,把android:fillViewport="true" 屬性家進入試一下。問題解決,看效果圖。

image

最重要的是將ScrollView中android:fillViewport設置為true。
當ScrollView里的元素想填滿ScrollView時,使用"fill_parent"是不管用的,必需為ScrollView設置:android:fillViewport="true"。

總結

當ScrollView沒有fillVeewport=“true”時,里面的元素(比如LinearLayout)會按照wrap_content來計算(不論它是否設了"fill_parent"),而如果LinearLayout的元素設置了fill_parent,那么也是不管用的,因為LinearLayout依賴里面的元素,而里面的元素又依賴LinearLayout,這樣自相矛盾.所以里面元素設置了fill_parent,也會當做wrap_content來計算.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容