问题:ADV遮挡ListView列表项,附布局代码寻求解决方案
(猜你说的ADV是AppBarLayout的笔误啦😉)
在使用CoordinatorLayout + AppBarLayout的布局结构时,ListView被顶部栏遮挡是很常见的问题,主要是因为滚动视图没有和AppBarLayout建立联动关系,我给你几个靠谱的解决办法:
1. 给ListView设置滚动联动Behavior(最推荐)
Design库提供了专门的Behavior来让滚动视图和AppBarLayout配合,只需要在你的ListView标签里添加app:layout_behavior属性,它会自动计算AppBarLayout的高度,给ListView加上合适的顶部偏移,完全避免遮挡:
<ListView android:id="@+id/your_list_view_id" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" />
这个behavior是系统内置的,只要你引入了Design库(android.support.design或者AndroidX的com.google.android.material:material)就能直接用。
2. 检查布局的fitsSystemWindows配置
确保你的CoordinatorLayout和AppBarLayout都正确设置了android:fitsSystemWindows="true",这个属性会让布局适配系统状态栏的高度,避免内容被状态栏和AppBarLayout双重遮挡:
<android.support.design.widget.CoordinatorLayout ... android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" ...> <!-- 里面的Toolbar等控件 --> </android.support.design.widget.AppBarLayout> <!-- 你的ListView --> </android.support.design.widget.CoordinatorLayout>
3. 手动添加顶部Padding(备选方案)
如果上面的Behavior方法不生效(比如特殊的布局场景),可以手动给ListView添加顶部Padding,值对应AppBarLayout的高度,同时开启clipToPadding=false让内容可以滚动到Padding区域:
<ListView android:id="@+id/your_list_view_id" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingTop="?attr/actionBarSize" android:clipToPadding="false" />
?attr/actionBarSize是系统内置的属性,对应Toolbar的默认高度,如果你自定义了AppBarLayout的高度,换成对应的数值或者自定义属性即可。
4. 考虑替换为RecyclerView(进阶推荐)
ListView虽然能解决问题,但RecyclerView在CoordinatorLayout中的联动效果更流畅,而且支持更多的布局类型和动画。如果项目允许的话,建议把ListView换成RecyclerView,同样使用app:layout_behavior="@string/appbar_scrolling_view_behavior"属性,体验会更好。
内容的提问来源于stack exchange,提问作者Christian Giupponi

