如果按照平常的设置,ScrollView里面的ListView是无法显示全部的,而且还不能滑动,从stackover flow搜的代码,亲测可以用!
1>给listView设置点击监视事件:
ListView lv = (ListView) findViewById(R.id.layout_lv);
lv.setOnTouchListener(new OnTouchListener() {
// Setting on Touch Listener for handling the touch inside ScrollView
@Override
public boolean onTouch(View v, MotionEvent event) {
// Disallow the touch request for parent scroll on touch of child view
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
2>给listView设置高度自适应的方法:
/**** Method for Setting the Height of the ListView dynamically. **** Hack to fix the issue of not showing all the items of the ListView **** when placed inside a ScrollView ****/ public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) return; int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.UNSPECIFIED); int totalHeight = 0; View view = null; for (int i = 0; i < listAdapter.getCount(); i++) { view = listAdapter.getView(i, view, listView); if (i == 0) view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT)); view.measure(desiredWidth, MeasureSpec.UNSPECIFIED); totalHeight += view.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); }
3>让listView应用该设置:
ListView list = (ListView) view.findViewById(R.id.ls); setListViewHeightBasedOnChildren(list);
ok,搞定~~~
时间: 2024-11-05 14:38:33