Android ScrollView 嵌套有ListView控件,ListView只显示一行数据问题。
在实际开发过程中,经常会碰到ScrollView中嵌套ListView的情景。
可是如果直接使用ScrollView嵌套ListView的话,我们会发现,ListView只能显示一行。
所以需要动态计算ListView 高度,如下代码:
private HomeAdapter adapter; private List<GoodsBean> goods; private ListView ll_goods; ll_goods = view.findViewById(R.id.ll_goods); adapter = new HomeAdapter(getContext()); goods = new ArrayList<>(); goods.add(new GoodsBean("百仙草1",300f,"含有人体所需的【叶绿素】","权益积分 9000")); goods.add(new GoodsBean("百仙草2",300f,"含有人体所需的【叶绿素】","权益积分 9000")); goods.add(new GoodsBean("百仙草3",300f,"含有人体所需的【叶绿素】","权益积分 9000")); adapter.setDataList(goods); ll_goods.setAdapter(adapter); adapter.notifyDataSetChanged(); int totalHeight = 0; for (int i = 0, len = adapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目 View listItem = adapter.getView(i, null, ll_goods); // 计算子项View 的宽高 listItem.measure(0, 0); // 统计所有子项的总高度 totalHeight += listItem.getMeasuredHeight(); }
ViewGroup.LayoutParams params = ll_goods.getLayoutParams(); params.height = totalHeight+ (ll_goods.getDividerHeight() * (adapter.getCount() - 1)); // listView.getDividerHeight()获取子项间分隔符占用的高度 // params.height最后得到整个ListView完整显示需要的高度 ll_goods.setLayoutParams(params);