轉自?http://blog.csdn.net/fzh0803/article/details/7971391
由于scrollview和listview不能直接共存,在scrollview中直接使用lsitview的話只會顯示一個條目,要使他們共存,
據我所知,有三種方法:
1。如果listview的高度是一定的話,可以重寫一個listview在onmesure方法里設定固定高度,如下代碼:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
?? ?super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0) );?
? ? ? ? int childHeight = getMeasuredHeight() - (getListPaddingTop() + getListPaddingBottom() + ?getVerticalFadingEdgeLength() * 2);?
? ? ? ? int fullHeight = getListPaddingTop() + getListPaddingBottom() + childHeight*(getCount());?
? ? ? ? setMeasuredDimension(getMeasuredWidth(), fullHeight);?}
2.如果listview中的高度不是固定的,可以在初始化完listview后設置listview的高度。可以使用以下函數:
public void setListViewHeightBasedOnChildren(ListView listView) {
? ? ? ? SettingListAdapter listAdapter = (SettingListAdapter) listView.getAdapter();?
? ? ? ? if (listAdapter == null) {
? ? ? ? ? ? return;
? ? ? ? } ? ? ??
? ? ? ? int totalHeight = 0;
? ? ? ? for (int i = 0; i < listAdapter.getCount(); i++) {
? ? ? ? ? ? View listItem = listAdapter.getView(i, null, listView);
? ? ? ? ? ? if(listItem != null){
? ? ? ? ? ? ? ? listItem.setLayoutParams(new LayoutParams(
? ? ? ? ? ? ? ? ? ? ? ? LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
? ? ? ? ? ? ? ? listItem.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
? ? ? ? ? ? ? ? totalHeight += listItem.getMeasuredHeight();
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? ViewGroup.LayoutParams params = listView.getLayoutParams();
? ? ? ? params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))?
? ? ? ? ? ? ? ? + listView.getPaddingTop() + listView.getPaddingBottom();
? ? ? ? listView.setLayoutParams(params);
? ? }
這樣就可以使listview設定為正確高度。
3.用一個linearLayout來代替listview