gpt4 book ai didi

android - 如何计算 Android 上 ScrollView 内的 GridView 所需的高度?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:40 25 4
gpt4 key购买 nike

我在 ScrollView 中的 LinearLayout 中有一个 GridView,它从服务器分页数据。在 GridView 下方是一个用于加载更多数据的按钮。我的 GridView 的最终高度将大于屏幕。如果我将 GridView 的高度设置为 wrap_content 或 parent_fill,它会将自身调整为精确可用的屏幕高度并且根本不滚动,裁剪掉额外的行。如果我将 layout_height 显式设置为较大的值(例如 1000dip),则滚动会正常运行,但我无法先验预测 ScrollView 的最终高度。

如何以编程方式确定 GridView 的必要高度以获得所需的行为?

下面是我的布局。如您所见,我将高度设置为 1000dip,但那是假的,我需要自动/以编程方式设置该值:

        <ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_weight="1"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="1000dip"
android:columnWidth="70dp"
android:numColumns="auto_fit"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:background="#000000"
android:layout_weight="1"
/>
<Button
android:id="@+id/load_more"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Load More Foo"
/>
</LinearLayout>
</ScrollView>

最佳答案

如果有人需要,这里有一种方法可以做到这一点。有点hack,但可以解决问题。您必须将 GridView 初始设置得足够大以容纳所有 View (例如 10000dip)

final GridView imageContainer = // your GridView
imageContainer.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
imageContainer.getViewTreeObserver().removeGlobalOnLayoutListener( this );
View lastChild = imageContainer.getChildAt( imageContainer.getChildCount() - 1 );
imageContainer.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, lastChild.getBottom() ) );
}
});

关于android - 如何计算 Android 上 ScrollView 内的 GridView 所需的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3682445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com