先大致描述一下,在ScrollView中嵌ListView会出现ListView显示不全的情况。
在网上找了很久,在stackoverflow有人给出了解决方案:
public static class Utility {
public static 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项高度一样的情况下能用,一旦高度不固定,还是会有显示不全的问题。
好吧,不满足我的需求,只能继续寻找,终于,皇天不负有心人,让哥找到了,这应该是目前为止最为简单不过的解决方式了,废话不多说下面先上代码:
package com.xxx.yyy;
import android.widget.ListView;
/**
*
* @Description: scrollview中内嵌listview的简单实现
*
*/
public class ScrollViewWithListView extends ListView {
public ScrollViewWithListView(android.content.Context context,
android.util.AttributeSet attrs) {
super(context, attrs);
}
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
也就是通过自定义一个ListView类,重载onMeasure()方法,设置为全部显示。
然后在你的xml布局中使用这个自定义的ListView,一切搞定,就这么简单,太方便了~
另外,在stackoverflow看到有另外的方案,这种方式是截断ScrollView上的滚动事件,让ListView自己滚动,看需求了,也许有人就是需要这种效果,一并贴出来了:
</pre><pre name="code" class="java">ListView lv = (ListView)findViewById(R.id.myListView); // your listview inside scrollview
lv.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
另外,在stackoverflow看到有另外的方案,这种方式是截断ScrollView上的滚动事件,让ListView自己滚动,看需求了,也许有人就是需要这种效果,一并贴出来了:
</pre><pre name="code" class="java">ListView lv = (ListView)findViewById(R.id.myListView); // your listview inside scrollview
lv.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});