Search code examples
androidandroid-actionbarandroid-toolbar

setting toolbar height programmatically doesn't work on android 4.4


I try to change the height of my toolbar programmatically:

ViewGroup.LayoutParams params =  toolbar.getLayoutParams();
params.height = (displayWidth / 1024) * 580;
toolbar.setLayoutParams(params);
toolbar.requestLayout();

the toolbar is defined like this in my xml:

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="5dp"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bbtest"
            android:minHeight="?attr/actionBarSize"
            android:longClickable="false">
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

on android 8.0 this works like a charm. But on my android 4.4.2 tablet the height of the toolbar reduces to zero when doing this.

Does anyone know why?


Solution

  • In your 4.4 device, the displayWidth is integer format and it < 1024 then (displayWidth / 1024) * 580 = 0.
    Therefore, it make your toolbar invisible.
    The solution is you can change displayWidth to float (or double) or change the operator to displayWidth * 580 / 1024