Search code examples
androidandroid-layoutandroid-toolbarback-button

Android: right margin at Up button on the Toolbar


I'm setting custom view into my Toolbar:

ActionBar actionBar = getSupportActionBar();
View customView = getLayoutInflater().inflate(resId, null);
actionBar.setCustomView(customView);
actionBar.setDisplayShowCustomEnabled(true);

It looks fine until I enabling Up button:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Here are pictures of the toolbar with Up button and without. I've added gray color to my custom view's background to view the real element size.

Without:
without

With:
with

And here is an image of Layout inspector window. There is a space between Up button and custom view.

layout inspector


Solution

  • Instead of this you have to write your own Up button:

    <ImageButton
        android:id="@+id/action_back"
        style="@style/Widget.AppCompat.ActionButton"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="center_vertical"
        android:onClick="onClick"
        app:srcCompat="@drawable/ic_arrow_back_white"
        tools:ignore="ContentDescription" />
    

    android:onClick="onClick" on your Button and сreate method in Java class like below way

    @Override
    public void onClick(View v) {
         NavUtils.navigateUpFromSameTask(TheoryActivity.this);
    }