本人在做评论回复功能的时候,查阅到ListView结合Adapter适配器具有以列表的形式 展示具体数据内容,并且能够根据数据的长度自适应屏幕显示的功能,因此打算在ListView中嵌套ListView完成点击事件后弹出输入框再输入数据后在下方显示回复内容(失败了),如图所示。
但是这只有一个ListView(回复内容的地方),并未将整个放入ListView。
原因是在进行ListView嵌套ListView时,出现只显示第一个ListView的内容,并未出现第二个ListView的展示内容(即点击事件后未展示评论回复功能)。
在查阅资料后,发现一个嵌套问题发现别人也有遇到这样的问题,而大多数人都不推荐这样的设计,因为默认情况下Android是禁止在ScrollView中放入另外的ScrollView的,它的高度是无法计算的。 然后就有什么牛人解决了调用静态方法、在子ListView的xml文件中重写,但都对我这个项目没有半点用,顺带介绍下吧,也希望能解决你的问题。
第一个思路就是在设置完ListView的Adapter后,根据ListView的子项目重新计算ListView的高度,然后把高度再作为LayoutParams设置给ListView,这样它的高度就正确了,源码如下:
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
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.setAdapter(ListViewAdapter);
Utility.setListViewHeightBasedOnChildren(ListView);
//此为子ListView
第二个思路是在子ListView的xml文件中引入该代码进行重定义高度,重写其onMeasure ()方法,源码如下:
public class CustomListView extends ListView {
public CustomListView(Context context) {
super(context);
}
public CustomListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public CustomListView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
用法如下:
<com.example.test.ChildListView
android:id="@+id/comment_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
以上对我项目没有用,终于在一篇文章中发现了跟我项目有类似的问题(对以上免疫),它的解决方法是要求子ListView的高度必须是match_parent,而且在子ListView文件XML中必须和它的布局一样,确实能够在ListView中显示ListView了,不再是空白一片,链接如下:
(150条消息) ListView嵌套ListView导致数据展示不全的终极解决方案_吴先生已被占用的博客-CSDN博客https://blog.csdn.net/qq_31296231/article/details/78929647 但是布局都match_parent不满足我开发的需求,故放弃ListView嵌套ListView的方法,下篇介绍利用ExpandableListView解决评论回复功能。