首页 > 学院 > 开发设计 > 正文

ScrollView 嵌套 ListView or ExpandableListView显示问题(一行属性搞定)

2019-11-06 09:41:39
字体:
来源:转载
供稿:网友

前言

项目中难免会用到滚动视图嵌套列表的情况

ScrollView

若一个手机屏幕的大小都不能够显示整个页面的话,最外层根视图可以考虑使用ScrollView

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"></ScrollView>

当然,使用ScrollView也会有一个局限性。 相信大家应该也都了解到 ScrollView 的子布局只允许有一个,否则XML的编译也会报错。

这里写图片描述

ScrollView嵌套列表出现的问题

这是一个根视图为ScrollView 的XML布局,里面嵌套的是ListView。然后就会出现列表内容只显示了一个Item。就算有多组数据,列表也只会显示一个。

这里写图片描述

根据以往的经验,可能会想到去动态的计算出每一个Item的宽高才可以完全显示,这也算是一种办法。但是没办法在PReview中查看ListView是否真的显示完整,只能通过运行到模拟器或者真机上调试看效果。 动态计算每一个Item的代码:

public static void setListViewHeightBasedOnChildren(ExpandableListView listView) { //获取ListView对应的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition 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);}

这并不是我们最终想要的效果。 其实只要在根视图中加一行 android:fillViewport="true" 就可以了。 不管内部嵌套的是ListView 还是ExpandableListView 都能完美解决这个问题。

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:fillViewport="true"> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content"/></ScrollView>

这里写图片描述


上一篇:runtime学习笔记

下一篇:进程与线程详解

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表