Android开发:CardView滚动后间距异常增大问题求助
看起来你遇到的这个滚动后CardView间距异常增大的问题,大概率是RecyclerView的高度设置不当导致的,结合你提供的布局代码,我来帮你拆解一下:
核心问题所在
你的content_main.xml里,RecyclerView的android:layout_height设为了wrap_content,同时它的父布局LinearLayout也用了wrap_content,再加上和AppBarLayout配合的app:layout_behavior="@string/appbar_scrolling_view_behavior",这几个因素叠加,会让RecyclerView在滚动过程中出现测量错误,错误地为每个item分配了远大于实际需要的空间,最终表现为卡片间出现一屏高的间距。
修复步骤
修改RecyclerView的高度为
match_parent
把content_main.xml里RecyclerView的layout_height从wrap_content改成match_parent,让RecyclerView占据父布局的全部可用空间,这样滚动时的测量逻辑就会正常工作。修改后的代码如下:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".MainActivity" tools:showIn="@layout/activity_main"> <android.support.v7.widget.RecyclerView android:id="@+id/program_view" android:layout_width="match_parent" android:layout_height="match_parent" <!-- 这里修改为match_parent --> android:orientation="vertical"/> </LinearLayout>确认LayoutManager的正确设置
另外请确保你在代码中给RecyclerView设置了正确的LayoutManager,比如垂直方向的LinearLayoutManager:RecyclerView programView = findViewById(R.id.program_view); programView.setLayoutManager(new LinearLayoutManager(this)); programView.setAdapter(yourProgramAdapter);如果没有设置LayoutManager,RecyclerView的布局行为也会出现异常,不过从你滚动前显示正常的情况来看,你大概率已经设置了,但还是建议检查一下。
额外说明
你的CardView布局本身没有太大问题,android:layout_marginBottom="5dp"可以正常控制卡片间的间距,cardUseCompatPadding和cardPreventCornerOverlap的设置也不会导致这种滚动后的异常间距,所以核心修复点还是RecyclerView的高度设置。
内容的提问来源于stack exchange,提问作者ARotov

