【发布时间】:2014-03-13 07:24:23
【问题描述】:
我在ScrollView 中使用ListView,众所周知,它会产生问题。
我从这个网站得到了很好的解决方案:How to calculate total row heights of listView in android?
但是对于某些项目,它没有正确显示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 - 20;
int widthSpec = MeasureSpec.makeMeasureSpec(listViewWidth,
MeasureSpec.AT_MOST);
listItem.measure(widthSpec, 0);
totalHeight += listItem.getMeasuredHeight();
Log.e("height of listItem:", String.valueOf(totalHeight));
}
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
myListView.setLayoutParams(params);
myListView.requestLayout();
}
【问题讨论】:
-
@BhanuSharma,查看更新后的帖子。
-
@AhmedHafez,我已经尝试过了,我的解决方案比那个更好。
标签: android listview android-listview