【发布时间】:2014-04-16 06:52:16
【问题描述】:
具有不同大小项目的 ScrollView 内不可滚动的 ListView。实际上,我尝试获取列表项的数量并给出高度=项目数量*第一项的高度,但问题是我在列表中有不同高度的项目,所以最后一项有时不可见。 这是我的自定义列表视图:
public class ExpandedListView extends ListView {
private android.view.ViewGroup.LayoutParams params;
private int old_count = 0;
int limit=0;
public ExpandedListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
if (getCount() != old_count) {
old_count = getCount();
params = getLayoutParams();
int height=0;
int h =getCount() * (old_count > 0 ? getChildAt(0).getHeight() : 0);
int minHeight=setListViewHeightBasedOnChildren(this);
if (h>minHeight) {
params.height=h+8 * (getCount() - 1)+25;
setLayoutParams(params);
}
super.onDraw(canvas);
}
}
public static int setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return 0;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1))+100;
listView.setLayoutParams(params);
return params.height;
}
}
【问题讨论】:
-
向我们展示你的努力。贴一些代码。
-
这段代码似乎没问题。尝试将
Margin bottom设置为您的列表视图并检查 -
问题是如果我有 20 dp 的第一项和 80 dp 和 60 dp 的第一项,则列表将需要 60 dp 高度(20 * 3),但它应该需要 20+80+60=160dp。我该怎么办???
-
listItem.getMeasuredHeight();将获得单个项目的高度,无论它是什么。它将添加高度并更新!不是通过在高度上再增加 100 dp 来工作吗? -
我们只能通过 getChildAt(1).getHeight() 或在其他位置给 null 来获取第一项的高度。如果我在适配器中使用它,它会返回 0。