如何使AppBarLayout中的Toolbar实现背景透明?
如何让AppBarLayout中的Toolbar背景透明?
当然可以搞定这个问题!我来给你说几个关键步骤,轻松实现透明Toolbar的效果:
先处理AppBarLayout的背景和阴影
AppBarLayout默认会继承主题的背景色,这就是你看到白色背景的原因。直接在布局里给它设置透明背景,同时移除默认的阴影(不然阴影会让视觉上看起来还是有“伪背景”):<android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/transparent" app:elevation="0dp">再设置Toolbar本身的背景为透明
确保Toolbar本身的背景也是透明的,不然它自己的背景会盖过AppBarLayout的设置:<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@android:color/transparent" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
把这些整合到你的完整布局里,大概是这样:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?attr/activityBackgroundColor" > <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/transparent" app:elevation="0dp"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@android:color/transparent" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> </android.support.design.widget.AppBarLayout> <!-- 这里放你的滚动内容布局,比如NestedScrollView或RecyclerView --> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <!-- 你的页面内容 --> </android.support.v4.widget.NestedScrollView> </android.support.design.widget.CoordinatorLayout>
额外提醒一下:如果你的项目已经迁移到Material Components库(使用com.google.android.material.appbar.AppBarLayout和com.google.android.material.appbar.MaterialToolbar),这些设置完全通用,只需要替换对应的组件类名就行。另外,检查一下你的Toolbar主题或样式,别在样式里硬设置了背景色,不然会覆盖这里的透明设置。
内容的提问来源于stack exchange,提问作者Rafael
相关产品推荐
相关产品推荐

