大概需求是这样的,listview下有一个按钮,会显示不全,我准备在外面嵌套一层scrollview,这样可以做到可以滑动,于是我加了这样一段代码
<ScrollView
android:id=
"@+id/scroll_view"
android:layout_width=
"match_parent"
android:layout_height=
""
android:layout_marginTop=
"10dp"
android:fillViewport=
"true" >
<LinearLayout
android:layout_width=
"match_parent"
android:layout_height=
"wrap_content"
android:orientation=
"vertical" >
...
</LinearLayout >
</ScrollView>
加完之后我发现listview无法正常显示,只能显示一条Item,其实想想很明显,scrollview的高度是根据子view的高度设定的,listview的高度在初始化的时候,
并不是全部的高度,要在加了adapter之后才有全部的高度。
/**
*
* setListViewHeightBasedOnChildren:这个方法可以根据adapter重设 listview的高度,
* 解决 scrollview嵌套listview时,listview无法全部显示的异常
*
*
@param
@param
listView 设定文件
*
@return
void DOM对象
*
@throws
*
@since
CodingExample Ver 1.1
*/
public
static
void
setListViewHeightBasedOnChildren(ListView listView)
{
ListAdapter listAdapter = listView.getAdapter();
if
(listAdapter ==
null
)
{
// pre-condition
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);
}
这个方法可以根据adapter里面item的数目重新设置listview的高度