且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android 如何在一个活动中一个接一个地显示 2 个列表视图

更新时间:2023-02-01 21:10:20

像这样使用:

删除线性布局.使用相对布局并在其中放置两个列表视图,如下所示.

Remove Linear layout. use relative layout and inside that place your two list view like this.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/scrollojt"
android:fillViewport="true" >

   <RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f00" >
 </ListView>

 <ListView
android:id="@+id/listView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/listView1"
android:background="#0f0" >
</ListView>
    </RelativeLayout>
  </ScrollView>

添加 Utility.java

public class Utility {

    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();
    }
}

在您的活动中:

 lv1.setAdapter(adapter);
 lv2.setAdapter(adapter);

Utility.setListViewHeightBasedOnChildren(lv1);
Utility.setListViewHeightBasedOnChildren(lv2);