1、手动设置ListView高度
经过测试发现,在xml中直接指定ListView的高度,是可以解决这个问题的,但是ListView中的数据是可变的,实际高度还需要实际测量。于是手动代码设置ListView高度的方法就诞生了。
public
void
setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if
(listAdapter ==
null
) {
return
;
}
int
totalHeight =
0
;
for
(
int
i =
0
; i < listAdapter.getCount(); 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
));
listView.setLayoutParams(params);
}
上面这个方法就是设定ListView的高度了,在为ListView设置了Adapter之后使用,就可以解决问题了。
但是这个方法有个两个细节需要注意:
一是Adapter中getView方法返回的View的必须由LinearLayout组成,因为只有LinearLayout才有measure()方法,如果使用其他的布局如RelativeLayout,在调用listItem.measure(0, 0);时就会抛异常,因为除LinearLayout外的其他布局的这个方法就是直接抛异常的,没理由…。我最初使用的就是这个方法,但是因为子控件的顶层布局是RelativeLayout,所以一直报错,不得不放弃这个方法。
二是需要手动把ScrollView滚动至最顶端,因为使用这个方法的话,默认在ScrollView顶端的项是ListView,具体原因不了解,求大神解答…
2、使用单个ListView取代ScrollView中所有内容
就是说,把整个需要放在ScrollView中的内容,统统放在ListView中,原ListView上方的数据和下方数据,都作为现ListView的一个itemView,和原ListView中的单条数据是平级的关系。
3、使用LinearLayout取代ListView
4、自定义可适应ScrollView的ListView
这个方法和上面的方法是异曲同工,方法3是自定义了LinearLayout以取代ListView的功能,但如果我脾气就是倔,就是要用ListView怎么办?那就只好自定义一个类继承自ListView,通过重写其onMeasure方法,达到对ScrollView适配的效果。
public
class
MyListView
extends
ListView {
public
MyListView(Context context) {
super
(context);
}
public
MyListView(Context context, AttributeSet attrs) {
super
(context, attrs);
}
public
MyListView(Context context, AttributeSet attrs,
int
defStyle) {
super
(context, attrs, defStyle);
}
@Override
protected
void
onMeasure(
int
widthMeasureSpec,
int
heightMeasureSpec) {
int
expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >>
2
,
MeasureSpec.AT_MOST);
super
.onMeasure(widthMeasureSpec, expandSpec);
}
}