ScrollView中嵌套ListView的动态高度问题


问题

昨天写代码时突然遇到一个问题,当ListView处于ScrollView中时,如果动态的给ListView添加数据的话,并不会显示多行,仅显示一行。

开始我以为是数据或者adapter的问题,检查了好多遍发现没问题,后来就一点点调试,发现ListView的高度是固定的,why?

网上找到的答案是因为ListViewScrollView的自动调节高度会冲突,解决的办法是自己去动态设置ListView要的高度。

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
** yjhxqlistForLsjl 数据集合
*/
private void loadListViewForLsjl(){
adapter = new XlHistoryAdapter(this, yjhxqlistForLsjl);//初始化adapter
adapter.enableCheck(false);
adapter.enableDelete(false);
mListViewForLsjl.setAdapter(adapter);//ListView设置adapter
ListAdapter listAdapter = adapter;//获得监听
View item = listAdapter.getView(0, null, mListViewForLsjl);
item.measure(0, 0);//设置测量模式
ViewGroup.LayoutParams params = mListViewForLsjl.getLayoutParams();
params.height = (yjhxqlistForLsjl.size()-1)*item.getMeasuredHeight()+item.getMeasuredHeight();
mListViewForLsjl.setLayoutParams(params);
}

可以看到其中有这么一段:

1
2
3
4
5
6
7
8
9
{
...
View item = listAdapter.getView(0, null, mListViewForLsjl);
item.measure(0, 0);
ViewGroup.LayoutParams params = mListViewForLsjl.getLayoutParams();
params.height = (yjhxqlistForLsjl.size()-1)*item.getMeasuredHeight()+item.getMeasuredHeight();
mListViewForLsjl.setLayoutParams(params);
...
}

这么写是为了获取ListView每一个Item的高度。刚开始获取高度我是这么写的:

1
mListViewForLsjl.getDividerHeight();

之后发现不管多少数据,这个高度返回值都是1,可能是我没太理解getDividerHeight的意思。所以就采用了上面那种方式通过measure(关于measure的使用大家可以看看这篇博文,讲的浅显易懂)来动态的获取Item的高度。

问题是解决了,但以后还是要尽量避免ScrollView嵌套ListView的情况,毕竟解决方案不算完美,这种处理方式还是存在隐患的。

-------------本文结束,感谢您的阅读-------------

本文标题:ScrollView中嵌套ListView的动态高度问题

文章作者:饭饭君~

发布时间:2018年11月27日 - 10:05

最后更新:2019年04月23日 - 10:50

原始链接:https://yangcf.github.io/2018/11/27/ScrollView中嵌套ListView的动态高度问题/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

如果我的文章有帮助到你,欢迎打赏~~
0%