您的位置:首页 > 其它

ScrollView与ListView的冲突问题

2013-06-02 17:49 351 查看
今天在实现ScrollView中嵌套多个ListView的时候,出现了ListView不能正常显示的情况,总结下遇到的问题以及解决方案。

ScrollView can host only one direct child
在往ScrollView中添加子项的时候往往是多个子项一起添加的,但是系统会提示错误。

这是因为ScrollView中只能有一个子项,所以这里我将所有的子项全部放在一个Layout中。

<ScrollView
android:id="@+id/ScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffffff"
android:scrollbars="vertical" >

<LinearLayout
android:id="@+id/tmall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文本备忘"
android:textSize="28sp" />

<ListView
android:id="@+id/listview0"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="智能备忘"
android:textSize="28sp" />

<ListView
android:id="@+id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>


 

ListView只显示一行多一点
这个我的解决方法是参考网络上的做法,通过给ListView设置LayoutParams属性来改变。

public class ListViewUtils {
public void setListViewHeightBasedOnChildren(ListView listView) {
// 获取ListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}

int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0); // 计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
}

ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
// listView.getDividerHeight()获取子项间分隔符占用的高度
// params.height最后得到整个ListView完整显示需要的高度
listView.setLayoutParams(params);
}
}


然后只要在初始化listview后使用就行了

private void initView() {
textListView = (ListView) findViewById(R.id.listview0);
intelListView = (ListView) findViewById(R.id.listview1);

textListView.setAdapter(new MyTestAdapter(this));
intelListView.setAdapter(new MyTestAdapter(this));

new ListViewUtils().setListViewHeightBasedOnChildren(textListView);
new ListViewUtils().setListViewHeightBasedOnChildren(intelListView);
}


 

 

到此,问题基本解决

ps:这是我的第一篇博客,多有不足,希望读者能多给建议

本文参考自:http://jackxlee.blog.51cto.com/2493058/666475
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: