如何在Android中的单个布局中添加两个列表视图

时间:2014-07-24 17:47:20

标签: android listview android-listview

您好我正在开发演示应用程序,我需要在第二个listview之后添加两个listview首先listview

我正在尝试如下,但如果我在第一个listview中添加更多项目,则第二个listview项目不会显示,因为完整的全屏高度占据了listview

我希望它应该滚动而不是第二个listview的小空格。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >

    <ListView
        android:id="@+id/firstListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

    <ListView
        android:id="@+id/secondListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp" >
    </ListView>

</LinearLayout>

提前致谢。

2 个答案:

答案 0 :(得分:0)

使用它,对我来说很好用

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <ListView
        android:id="@+id/firstListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

    <ListView
        android:id="@+id/secondListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_below="@id/firstListView">
    </ListView>

</RelativeLayout>

答案 1 :(得分:0)

这解决了我的问题。这样就可以在一个activity中逐个list添加两个列表视图。

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}