为了屏幕适配,包含多元素的布局一般都会使用ScrollView
,以便小屏手机滑动查看,但是在大屏手机上内容全部加载,导致下方空白
我们希望最后的Button是置底的,同时是可以跟随滑动的
例如定义布局xml如下:
- <span style=“font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;”><?xml version=“1.0” encoding=“utf-8”?>
- <ScrollView xmlns:android=“http://schemas.android.com/apk/res/android”
- android:layout_width=“match_parent”
- android:layout_height=“match_parent” >
- <LinearLayout
- android:layout_width=“match_parent”
- android:layout_height=“match_parent”
- android:orientation=“vertical”>
- <LinearLayout
- android:layout_height=“350dp”
- android:layout_width=“match_parent”
- android:orientation=“vertical”
- android:background=“#ffffff00”>
- <TextView
- android:layout_width=“fill_parent”
- android:layout_height=“wrap_content”
- android:text=“content”/>
- </LinearLayout>
- <LinearLayout
- android:layout_height=“match_parent”
- android:layout_width=“match_parent”
- android:orientation=“horizontal”>
- <Button
- android:layout_width=“match_parent”
- android:layout_height=“45dp”
- android:layout_gravity=“bottom”/>
- </LinearLayout>
- </LinearLayout>
- </ScrollView></span>
<span style="font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;"><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_height="350dp"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="#ffffff00">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="content"/>
</LinearLayout>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_gravity="bottom"/>
</LinearLayout>
</LinearLayout>
</ScrollView></span>
运行效果是这个样子:
原因就是当子布局高度小于ScrollView的高度时,定义子布局match_parent或者fill_parent不起作用,因此设置layout_gravity也不起作用
在scrollview里添加属性android:fillViewport=”true” 就可以了,使得子布局高度和scrollview一样,而当子布局高度超过scrollview的高度时,这个属性就没有意义了
Romain Guy write a little info about a ScrollView attribute that is missing from documentation :android:fillViewport=”true” .
It must be set to ScrollView and has the following efect : when set to true, this attribute causes the scroll view’s child to expand to the height of the ScrollView
if needed. When the child is taller than the ScrollView
, the attribute has no effect.
添加属性后的效果图: