Android开发

ScrollView只显示最后一个控件

2021-12-06  本文已影响0人  卓技卓品

因为诗词的数据有可能较多,一屏不一定显示完,所以使用ScrollView实现滑动显示。但是发现当最后一个条目内容很多(ScrollView嵌套的LinearLayout最后一个TextView独自能够占满一屏)时,会出现只显示最后一个控件的现象。

实现代码如下:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="30dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_shici_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="18sp"
            android:paddingBottom="10dp"/>
        <TextView
            android:id="@+id/tv_shici_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="25dp"
            android:textSize="22sp"/>
    </LinearLayout>
</ScrollView >

当tv_shici_content控件中内容足够占满一屏时,无论如何都无法滚动显示tv_shici_title控件。
最初我考虑是tv_shici_content这个控件抢占了ScrollView的焦点,导致ScrollView无法获取滑动手势。但是当我给所有TextView、LinearLayout设置android:focusable="false"也不可用。
查阅资料,发现网络上基本上都是ScrollView嵌套ListView只显示一条的解决方案。那么我这个问题应该并不常见才对。
我尝试简化代码,直到移除了android:layout_gravity="center",功能竟然神奇的实现了。
最终代码是:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="30dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_shici_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="18sp"
            android:paddingBottom="10dp"/>
        <TextView
            android:id="@+id/tv_shici_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="25dp"
            android:textSize="22sp"/>
    </LinearLayout>
</ScrollView >

最终问题解决了,但是糊里糊涂的,没有明白为何会这样。在Android官方也没有找到答案。

网络上有人猜测说,ScrollView为了满足android:layout_gravity="center"功能,会将内容截取一整屏幕,然后实现居中显示,那么未被截取的内容就不会显示了。不确定这个猜测是否正确,暂且作为一个遗留问题吧。

上一篇 下一篇

猜你喜欢

热点阅读