背景
最近在开发项目中遇到一个问题,布局高度在小屏幕手机上高度不够全部显示,于是使用了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来计算.
网友评论