ScrollView嵌套ListView、RecyclerView高度自适应

ScrollView嵌套ListView或RecyclerView。可能导致ListView和RecyclerView显示不完整,高度无法完全展开。

ListView

针对ScrollView嵌套ListView时只显示第一个item高度的bug,可在Activity里动态修改ListView的高度(即计算每个item和分割线的高度后进行相加得到总高度),在setAdapter之后调用下面这个函数即可。

值得注意的是,此时ListView的子item根布局应设为LinearLayout。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void setListViewHeightBasedOnChildren(ListView listView) {
if (listView == null) {
return;
}
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
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);
}

RecyclerView

针对ScrollView嵌套RecyclerView时显示不完整的bug,直接在RecyclerView外嵌套一层RelationLayout即可解决。

1
2
3
4
5
6
7
8
9
10
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :