天天看點

Toolbar 自定義布局去除左右兩邊間距

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 自定義布局去除左右兩邊間距

網上查找去除左邊間距的方法都說在布局中設定 toolbar 一個屬性就可以了,如下:

app:contentInsetStart=”0dp”

但是加上後的效果是這樣的:

Toolbar 自定義布局去除左右兩邊間距

隻不過是間距變窄了一些。經過測試,發現還要設定 toolbar 的 paddingLeft 和 paddingRight 值為 0,當然,直接設定 padding 為 0 也是可以的。加上之後終于沒有間距了:

Toolbar 自定義布局去除左右兩邊間距

如果在代碼裡設定了顯示傳回箭頭,即

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

,則需要給布局添加屬性設定:

app:contentInsetStartWithNavigation=”0dp”

設定前:

Toolbar 自定義布局去除左右兩邊間距

設定後:

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"
        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 ~~~