【发布时间】:2016-10-14 20:42:23
【问题描述】:
我知道将两个 ListView 放在一个 ScrollView 中并不是最佳做法。但是,对于我的问题,这是我能想到的最佳解决方案:
我想要两个列表(第一个包含 1-5 个项目,最后一个包含最多 20 个项目)在可滚动视图中彼此下方,每个列表都有自己的标题。 ListViews 本身不应该是可滚动的,它们应该只是改变高度来包装它们的内容。可滚动部分将由 ScrollView 处理。
由于 ListView 本身不支持此功能,因此我使用以下代码:
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();
Log.d("DEBUG", "TotalHeight:" + totalHeight);
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listAdapter.getCount() * listView.getDividerHeight());
listView.setLayoutParams(params);
listView.requestLayout();
}
但是,这会使 ListView 比它们应该的大大约 10 倍。如果我搜索我遇到的问题,我总能找到上述解决方案,但对我来说这似乎不起作用。
有没有办法修复我的代码,或者有更好的方法来解决这个问题?
XML:
<ScrollView 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"
tools:context="com.miscoriadev.svvirgoapp.fragments.frag_activiteiten"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_acti_komende_activiteiten"
android:textSize="32sp"
android:text="Komende activiteiten"
android:textColor="@color/TextColorDark"
android:gravity="center"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tv_acti_komende_activiteiten"
android:id="@+id/lv_komende_activiteiten">
</ListView>
<TextView
android:paddingTop="@dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="32sp"
android:text="Afgelopen activiteiten"
android:textColor="@color/TextColorDark"
android:gravity="center"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:id="@+id/tv_acti_afgelopen_activiteiten"
android:layout_below="@id/lv_komende_activiteiten"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tv_acti_afgelopen_activiteiten"
android:id="@+id/lv_afgelopen_activiteiten">
</ListView>
</RelativeLayout>
【问题讨论】:
-
您需要两个列表同时滚动并显示在同一个屏幕上?如果是这样,我建议将GridView 与 2 列一起使用。如果没有,我建议使用ViewPager 和TabLayout。这是一个如何做的教程:guides.codepath.com/android/…
-
不,我只是希望它们位于彼此下方,并且在一个可滚动的框架中有两个列表
-
我相信如果你使用水平的
ListViews而不是垂直的会更方便。我什至建议使用水平或垂直的RecyclerView。
标签: java android xml listview scrollview