Search code examples
androidandroid-layoutandroid-themeandroid-styles

Why is it not possible to set layout_height and layout_width for toolbar in theme with toolbarStyle?


Challenge: I am trying to set layout_height and layout_width for toolbar through a default toolbar theme like so:

within my theme I have:

<item name="toolbarStyle">@style/Toolbar</item>

and the Toolbar style:

<style name="Toolbar" parent="Widget.AppCompat.Toolbar">
    <item name="android:background">@color/colorBackground</item>
    <item name="android:titleTextColor">@color/colorTextToolbar</item>
    <item name="android:layout_height">?attr/actionBarSize</item>
    <item name="android:layout_width">match_parent</item>
</style>

Problem: layout_height and layout_width is not being taken from my theme, when I delete android:layout_height and android:layout_width from my Toolbar, the toolbar completely disappears with an error saying these properties are missing. Though android:background and android:titleTextColor are being taken from my theme actually.

What I tried: Here I read I would have to add <resources xmlns:android="http://schemas.android.com/apk/res/android"> at the top. This had no effect actually and already have <resources xmlns:tools="http://schemas.android.com/tools"> at the top.

Do you have any idea why this is not working? Might this be due to how the inflater takes attributes from the precedence of styling?

Update: it seems as if toolbarStyle doesnt allow to set height and width of toolbars. I guess that this might be defined somewhere within the android docs, though I can´t find out where exactly. When I click on toolbar object I find

public Toolbar(@NonNull Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, R.attr.toolbarStyle);
}

as Constructur, so it takes R.attr.toolbarStyleR.attr.toolbarStyle as argument and when I look at toolbarStyle attribute I can only see
<attr format="reference" name="toolbarStyle"/>, which doesnt give me a clue what "toolbarStyle" really sets. Is there a way to find this out?


Solution

  • You need to apply the style to the Toolbar:

      <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            style="@style/Toolbar"
            android:background="@android:color/transparent" />