我在ScrollView中使用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 - 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();
}发布于 2014-03-13 07:40:35
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();功能的核心是这三行,它试图度量每一个视图。listItem.measure(0,0)中的0等于MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
大多数情况下,它将计算列表视图的精确高度。有一个例外,当视图内容太多,并将包装行,即有许多行的文本。在这种情况下,您应该指定一个精确的widthSpec来度量()。因此,将listItem.measure(0, 0)更改为
// try to give a estimated width of listview
int listViewWidth = screenWidth - leftPadding - rightPadding;
int widthSpec = MeasureSpec.makeMeasureSpec(listViewWidth, MeasureSpec.AT_MOST);
listItem.measure(listViewWidth, 0)更新这里的公式
int listViewWidth = screenWidth - leftPadding - rightPadding;
enter code here这只是一个例子,说明如何估计listview的宽度,公式是基于这样一个事实,即listview的宽度≈屏幕的宽度。填充是由您自己设置的,这里可能是0 (以像素为单位获取屏幕尺寸)。此页面说明如何获得屏幕宽度。一般来说,它只是一个样本,你可以在这里写出你自己的公式。
https://stackoverflow.com/questions/22371791
复制相似问题