/**
* @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的每個Item必須是LinearLayout,不能是其他的,因為其他的Layout(如RelativeLayout)沒有重寫onMeasure(),所以會在onMeasure()時拋出異常。
2、 自定義ListView,重載onMeasure()方法,設置全部顯示
package com.meiya.ui;
import android.widget.ListView;
/**
*
* @Description: scrollview中內嵌listview的簡單實現
*
* @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,如果不設置,系統默認設置是顯示兩條
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
以上可以解決scrollView內嵌listView,但是有一個問題是第一次進入界面時動態加載listview的items后頁面會跳轉到listview的第一個子項,這很蛋疼,
無奈又不知道怎么解決,就先用
scrollView.post(new Runnable() {
//讓scrollview跳轉到頂部,必須放在runnable()方法中
@Override
public void run() {
scrollView.scrollTo(0, 0);
}
});
這個方法過度下,希望有知道的朋友還給點解決方案
3、使用scrollView +LinearLayout用addView()的方法添加列表。