使用Toolbar/ActionBar自定义布局时,左侧/右侧有一段无法使用

来源:互联网 发布:淘宝旺铺免费模板 编辑:程序博客网 时间:2024/05/01 22:18

解决方法:

1.给Toolbar加上app:contentInsetStart”="0dp"(左侧)或者“app:contentInsetEnd”="0dp"(右侧)

    <android.support.v7.widget.Toolbar        android:layout_width="match_parent"        android:layout_height="?android:actionBarSize"        app:contentInsetStart="0dp"        app:contentInsetEnd="0dp"        app:contentInsetLeft="0dp"        app:contentInsetRight="0dp">        <!-- 自定义的布局-->        <View            android:layout_width="match_parent"            android:layout_height="match_parent"            android:background="@android:color/holo_green_dark"/>    </android.support.v7.widget.Toolbar>
反正就是这4个属性,自己看着加就行

注意:我们这里用的是v7包下的Toolbar,所以要使用自定义的属性。如果你使用的是系统的Toolbar,则使用android:开头的属性才会生效。


2.使用自定义的风格

<resources>    <!-- Base application theme. -->    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">        <!-- Customize your theme here. -->        <item name="colorPrimary">@color/colorPrimary</item>        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>        <item name="colorAccent">@color/colorAccent</item>        <item name="android:actionBarStyle">@style/CustomActionBarStyle</item>    </style>    <style name="CustomActionBarStyle" parent="Widget.AppCompat.Light.ActionBar">        <item name="contentInsetStart">0dp</item>        <item name="contentInsetEnd">0dp</item>        <item name="contentInsetLeft">0dp</item>        <item name="contentInsetRight">0dp</item>    </style></resources>
原理和上一个方法相同,只不过这个是全局都有效的,推荐使用


问题现象附图及问题原理:

之所以把现象放在了解决方法后面,因为很多人只关心解决方法吧。有兴趣的可以继续看看为什么会出现这个问题。

1.问题:

如图,就是我们在使用Toolbar的自定义布局时,我们可以看到预览图上我们的自定义布局并没有铺满整个Toolbar,而是在左侧出现了一小段白边,这让我们很是苦恼

2.解决:

所以,为了消除这个白边,我们就可以使用上述的方法轻松解决。可以看到下图加上红线框的属性后,预览中的白边也消失了。那么为什么会出现这个白边呢?


3.原因:

其实这是由于系统的自定义属性造成的,找到系统ActionBar的自定义属性,我们可以看到有这样一个自定义的风格(具体使用的哪个风格应该会跟随系统和使用的兼容包有一定的差距,这里仅作实例,Toolbar也是继承了ActionBar的一些风格)


我猜想应该就是这两个属性造成了ActionBar和Toolbar的自定义布局出现了一小段不可用的padding的吧,所以当我们在自定义的风格或者Toolbar的属性中重写掉这个属性并赋值“0dp”后白边你就消失了


2 0