Android中为Toolbar添加底部边框的实现方法
实现Toolbar底部边框效果
嘿,我来帮你搞定这个Toolbar底部边框的需求!根据你想要的样式,这里有两种简单可行的方法:
方法一:使用Layer-List自定义背景(推荐)
这种方法不需要额外添加View,直接通过自定义drawable来实现背景+边框的效果,更简洁。
- 在
res/drawable目录下创建一个新的drawable文件,比如toolbar_bg.xml,写入以下代码:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 主背景色,和你原来的colorPrimary一致 --> <item> <shape android:shape="rectangle"> <solid android:color="@color/colorPrimary" /> </shape> </item> <!-- 底部边框,这里可以调整高度和颜色来匹配你要的样式 --> <item android:top="-2dp" android:right="-2dp" android:left="-2dp"> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#E0E0E0" /> <!-- 这里换成你想要的边框颜色 --> </shape> </item> </layer-list>
- 修改你的Toolbar布局,把原来的
android:background="@color/colorPrimary"替换成这个自定义drawable:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar_main" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/toolbar_bg" android:elevation="1dp" app:theme="@style/AppTheme" app:titleTextAppearance="@style/TitleText" app:title="你的标题"/>
方法二:添加底部分隔线View
如果觉得自定义drawable麻烦,也可以直接在Toolbar下方添加一个细View作为边框:
在包含Toolbar的布局文件里,给Toolbar后面加一个View:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar_main" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:elevation="1dp" app:theme="@style/AppTheme" app:titleTextAppearance="@style/TitleText" app:title="你的标题"/> <!-- 底部边框View --> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#E0E0E0"/> <!-- 边框颜色可自定义 -->
两种方法都能实现你要的底部边框效果,你可以根据自己的需求选一种~
内容的提问来源于stack exchange,提问作者Noisemt
相关产品推荐
相关产品推荐

