天天看點

使用Toolbar/ActionBar自定義布局時,左側/右側有一段空白無法使用

解決方法:

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,而是在左側出現了一小段白邊,這讓我們很是苦惱

使用Toolbar/ActionBar自定義布局時,左側/右側有一段空白無法使用

2.解決:

是以,為了消除這個白邊,我們就可以使用上述的方法輕松解決。可以看到下圖加上紅線框的屬性後,預覽中的白邊也消失了。那麼為什麼會出現這個白邊呢?

使用Toolbar/ActionBar自定義布局時,左側/右側有一段空白無法使用

3.原因:

其實這是由于系統的自定義屬性造成的,找到系統ActionBar的自定義屬性,我們可以看到有這樣一個自定義的風格(具體使用的哪個風格應該會跟随系統和使用的相容包有一定的差距,這裡僅作執行個體,Toolbar也是繼承了ActionBar的一些風格)

使用Toolbar/ActionBar自定義布局時,左側/右側有一段空白無法使用

我猜想應該就是這兩個屬性造成了ActionBar和Toolbar的自定義布局出現了一小段不可用的padding的吧,是以當我們在自定義的風格或者Toolbar的屬性中重寫掉這個屬性并指派“0dp”後白邊你就消失了

使用Toolbar/ActionBar自定義布局時,左側/右側有一段空白無法使用