Toolbar button gravity for extended toolbar

2019-03-21 03:12发布

Im trying to set the position of my back navigation icon in my extended toolbar as follows:

<android.support.v7.widget.Toolbar  xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:theme="@style/Toolbar"
    android:minHeight="@dimen/action_bar_height"
    app:buttonGravity="top"
    android:gravity="top"
    android:background="?attr/colorPrimary" />

Checking the sources of toolbar we can see the following:

private void ensureNavButtonView() {
    if (mNavButtonView == null) {
        mNavButtonView = new ImageButton(getContext(), null,
            R.attr.toolbarNavigationButtonStyle);
        final LayoutParams lp = generateDefaultLayoutParams();
        lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK);
        mNavButtonView.setLayoutParams(lp);
    }
}

Where mButtonGravity is assigned via

mButtonGravity = a.getInteger(R.styleable.Toolbar_buttonGravity, Gravity.TOP);

So reading this correctly, the gravity of my toolbar should already be Gravity.TOP if nothing is configured. However it looks like this:

enter image description here

2条回答
何必那么认真
2楼-- · 2019-03-21 03:36

I played around a bit and tested a couple of combinations and can say that button's gravity and android:minHeight don't want to be friends.

This should work fine:

<android.support.v7.widget.Toolbar  xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_height="@dimen/action_bar_height"
    android:layout_width="match_parent"
    app:theme="@style/Toolbar"
    android:minHeight="?attr/actionBarSize"
    android:gravity="top"
    android:background="?attr/colorPrimary" />
查看更多
相关推荐>>
3楼-- · 2019-03-21 03:44

If you want the icon on the top and the title on the bottom you can try something like this:

<Toolbar
    android:id="@+id/toolbar"
    android:layout_height="128dp"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:gravity="bottom" />

Using the attribute android:minHeight as the standard actionBarSize,the buttons and actions are positioned in the top. While using the attribute android:gravity you can set the position of the title at the bottom.

查看更多
登录 后发表回答