Android - 在ListView中滚动时展开/折叠元素

4

在此输入图像描述

我的场景如下:

一个带有两个选项卡的TabHost,每个选项卡内部都有一个ListView。

我想要实现的功能是:

当在选项卡中的ListView上下滚动时,滚动或折叠位于顶部的ImageView。

这意味着当我向下滚动时,ImageView将会消失。如果我向上滚动,ImageView将再次出现。

我想要在不使用ScrollView的情况下实现这一点(到目前为止它并没有产生很好的结果)。

我该如何实现这一功能?

2个回答

0

这是我的示例,其中我在滚动视图中使用了图像视图和列表视图。 您可以在XML中添加自己的两个选项卡,不会有任何区别。 希望这能帮到您。

Layout.xml

 <ScrollView
    android:id="@+id/sv_itemRank"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/img_item_image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:contentDescription="@string/empty"
            android:scaleType="centerCrop" />

        <ListView
            android:id="@+id/lv_items_lists"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@color/white"
            android:divider="@null"
            android:dividerHeight="0dp"
            android:scrollbars="none" >
        </ListView>
    </LinearLayout>
</ScrollView>

在填充ListView之后,我使用自定义适配器调用此函数来根据子项设置ListView的高度。我是在adapter.notifyDataSetChanged();之后完成的,你可以根据你的代码进行更改。

setListViewHeightBasedOnChildren(listview)的代码。

将你的listview作为参数传递。

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null)
        return;

    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
            MeasureSpec.UNSPECIFIED);
    int totalHeight = 0;
    View view = null;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        view = listAdapter.getView(i, view, listView);
        if (i == 0)
            view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
                    LayoutParams.WRAP_CONTENT));

        view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
        totalHeight += view.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

谢谢你的回答,这不是我想要的,但我会把它作为一个答案考虑。 - Jakub Holovsky

0

我知道这可能不是你想要的答案,但你可以保留scroolView(而且可能必须这样做)。

试着看一下this的帖子,它完美地解释了如何在scrollView中设置一些listViews。

希望能帮到你 :)

编辑:我找到了this。虽然它不是你要找的解决方案,但它使用了onScrollListener,我认为你可以适应这个答案来解决你的问题,如果有效,请告诉我!


谢谢,我之前也看过这个链接。不过还是希望避免使用它。还是谢谢你。 - Jakub Holovsky
@JakubHolovsky,我改进了答案,请查看我写的帖子并告诉我是否有效! :) - Pier Giorgio Misley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接