【发布时间】:2014-06-23 09:37:47
【问题描述】:
我在 Android 的 ScrollView 中使用 ListView。所以,众所周知,它会出现高度问题。为此,我使用以下代码设置ListView 大小:
public static void getListViewSize(ListView myListView, Context context) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
return;
}
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
if (listItem instanceof ViewGroup)
listItem.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
@SuppressWarnings("deprecation")
int screenWidth = display.getWidth();
int listViewWidth = screenWidth - 65;
int widthSpec = MeasureSpec.makeMeasureSpec(listViewWidth,
MeasureSpec.AT_MOST);
listItem.measure(widthSpec, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
myListView.setLayoutParams(params);
myListView.requestLayout();
}
Xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="@+id/lvHomeStream"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:divider="#b5b5b5"
android:dividerHeight="1dp" >
</ListView>
<TextView
android:id="@+id/tvMoreRecords"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginTop="10dp"
android:background="@drawable/list"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="@string/viewmore"
android:textColor="@color/blue"
android:textSize="16sp" />
</LinearLayout>
</ScrollView>
如果每个 ListView 项的高度相同,它就可以正常工作。但是,如果每个ListView 项目的高度异常,那么它会在ListView 结束边界和TextView 之间留下额外的大空间。
请帮我解决这个问题。
【问题讨论】:
-
这不是你的答案,但它不是将
listView放入ScrollView的好方法 -
listview 已经是一个滚动视图
-
根据您的要求,将 id 为 tvMoreRecords 的 textview 放在 listview 的页脚视图中,这样您就不需要在 scrollview 中使用 listview 了。
-
@shayanpourvatan,那我该怎么用呢?
-
@RaviBhatt,我知道,但是那样,它会在我不想要的固定位置显示
TextView。
标签: android listview android-listview