/**
* @param listView
*/
private 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的每個(gè)Item必須是LinearLayout,不能是其他的,因?yàn)槠渌腖ayout(如RelativeLayout)沒(méi)有重寫(xiě)onMeasure(),所以會(huì)在onMeasure()時(shí)拋出異常。
2、 自定義ListView,重載onMeasure()方法,設(shè)置全部顯示
package com.meiya.ui;
import android.widget.ListView;
/**
*
* @Description: scrollview中內(nèi)嵌listview的簡(jiǎn)單實(shí)現(xiàn)
*
* @File: ScrollViewWithListView.java
*
* @Paceage com.meiya.ui
*
*
* @Date 下午03:02:38
*
* @Version
*/
public class ScrollViewWithListView extends ListView {
public ScrollViewWithListView(android.content.Context context,
android.util.AttributeSet attrs) {
super(context, attrs);
}
/**
* Integer.MAX_VALUE >> 2,如果不設(shè)置,系統(tǒng)默認(rèn)設(shè)置是顯示兩條
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
以上可以解決scrollView內(nèi)嵌listView,但是有一個(gè)問(wèn)題是第一次進(jìn)入界面時(shí)動(dòng)態(tài)加載listview的items后頁(yè)面會(huì)跳轉(zhuǎn)到listview的第一個(gè)子項(xiàng),這很蛋疼,
無(wú)奈又不知道怎么解決,就先用
scrollView.post(new Runnable() {
//讓scrollview跳轉(zhuǎn)到頂部,必須放在runnable()方法中
@Override
public void run() {
scrollView.scrollTo(0, 0);
}
});
這個(gè)方法過(guò)度下,希望有知道的朋友還給點(diǎn)解決方案
3、使用scrollView +LinearLayout用addView()的方法添加列表。