Android Support Toolbar: Resizing won't realig

2019-05-07 14:41发布

问题:

I try to resize the Android Support Toolbar of my Activity on orientation change as it is too big in landscape mode. It's not automatically resized as I'm using

android:configChanges="orientation|screenSize"

on my activity and thus the activity won't be recreated. The toolbar XML is like this:

<android.support.v7.widget.Toolbar
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/my_awesome_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

in my onConfigurationChanged() I'm resizing the toolbar e.g. like this:

findViewById(R.id.my_awesome_toolbar).setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 114));

The result is not as expected. The menu items, which are populated using setSupportActionBar(toolbar); and the onCreateOptionsMenu() aren't correctly vertically aligned and neither is the navigation icon (toolbar.setNavigationIcon(...):

Anyone know of a better way to resize the toolbar or do I need to use workarounds like removing and readding the toolbar to the view stack?

回答1:

Just call setMinimumHeight for toolbar and it will work.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Toolbar tb = getActionBarToolbar();
    if (tb != null) {
        int size = UIUtils.calculateActionBarSize(this);
        tb.setMinimumHeight(size);
        ViewGroup.LayoutParams lp = tb.getLayoutParams();
        lp.height = size;
        tb.setLayoutParams(lp);
    }
}