v7 支持包中的 Toolbar,既可以直接代替 actionBar 使用,也可以嵌套布局自定义actionBar 样式,但是在嵌套布局自定义样式的时候,左右两边总会有一定的间距。直接在 toolbar 中添加布局:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/holo_blue_bright">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_dark" />
</android.support.v7.widget.Toolbar>
toolbar 背景为蓝色,自定义布局背景为红色,默认是这样的:
网上查找去除左边间距的方法都说在布局中设置 toolbar 一个属性就可以了,如下:
app:contentInsetStart=”0dp”
但是加上后的效果是这样的:
只不过是间距变窄了一些。经过测试,发现还要设置 toolbar 的 paddingLeft 和 paddingRight 值为 0,当然,直接设置 padding 为 0 也是可以的。加上之后终于没有间距了:
如果在代码里设置了显示返回箭头,即
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
,则需要给布局添加属性设置:
app:contentInsetStartWithNavigation=”0dp”
设置前:
设置后:
可以看到,返回箭头占的位置变窄了。
最后,完整布局是这样的:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/holo_blue_bright"
android:padding="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_dark" />
</android.support.v7.widget.Toolbar>
PS:使用 toolbar 代替 actionBar 时别忘了设置 Activity 主题为 NoActionBar ~~~