Search code examples
androidtoolbarandroid-custom-view

When add a custom view in Android Toolbar, there will be a marginLeft


I have some problems about android toolbar. Normally if I set a custom view into toolbar, the view should fill the whole toolbar space from left to right and has no margin.

but mine has a empty space in the left , these are my code :

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/base_toolbar"
        android:layout_width="match_parent"
        android:layout_height="46dip"
        android:background="?attr/colorPrimary" />

    <FrameLayout
        android:id="@+id/base_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

activity:

private void initToolbar() {
    toolbar = (Toolbar) findViewById(R.id.base_toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if( actionBar != null)
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    contentLayout = (FrameLayout) findViewById(R.id.base_content);
}

Is here anything wrong with my code or it should be like this ?


Solution

  • The space on the left is caused by Toolbar's contentInsetStart which by default is 16dp. You can set it to 0 to remove it. Dont forget to add the schema.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <android.support.v7.widget.Toolbar
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/base_toolbar"
            android:layout_width="match_parent"
            android:layout_height="46dip"
            android:background="?attr/colorPrimary"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp" />
    
        <FrameLayout
            android:id="@+id/base_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </LinearLayout>