LinearLayout在ScrollView Android内部被切断



我的应用程序中有一个活动,我希望用户能够垂直滚动LinearLayout中包含的内容,而又在ScrollView内。 下面是此活动的布局 XML 外观的摘要:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:orientation="vertical">
<!-- a bunch of standard widgets, omitted for brevity -->
<!-- everything renders but starting in this TextView -->
<!-- content begins to get truncated -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:gravity="left"
android:textSize="20dip"/>
<!-- this View, really just a trick for a horizontal row, is -->
<!-- completely cutoff -->
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@color/green" />
</LinearLayout>
</ScrollView>
</LinearLayout>

我观察到的是,内LinearLayout中的内容在ScrollView内被切断了。 在上面的最后TextView中,当它包含很少的文本时,它下面的View会以纵向呈现,但不会以横向呈现。 当此TextView包含大量文本时,它会在纵向模式下被切断。

我尝试了我在Stack Overflow上找到的建议。 向ScrollView添加底部填充并不能解决问题,将ScrollView换成NestedScrollView也没有解决问题。

欢迎任何有用的建议。 这实际上是一个障碍。

将内LinearLayout的边距更改为填充。或者,如果您确实需要它作为边距(也许您正在使用自定义背景(,请将您的LinearLayout包装在FrameLayout中。

ScrollView正在从LinearLayout中获取其高度(或者更准确地说,它正在计算其可滚动范围(。这个值不包括边距,所以你的ScrollView将被LinearLayout的上边距和下边距之和"太短"。

测量时忽略边距,请参阅此处

因此,您可以为ScrollView提供填充,并从LinearLayout中删除边距

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- a bunch of standard widgets, omitted for brevity -->
<!-- everything renders but starting in this TextView -->
<!-- content begins to get truncated -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:gravity="left"
android:textSize="20dip"/>
<!-- this View, really just a trick for a horizontal row, is -->
<!-- completely cutoff -->
<View
android:layout_width="match_parent"
android:layout_height="2dip"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@color/green" />
</LinearLayout>
</ScrollView>

此外,fill_parent在 API 级别 8 及更高版本中已弃用并重命名match_parent

最新更新