Search code examples
androidandroid-studioandroid-themeandroid-styles

Don't understand sintaxis using ? in textAppearance


I have been learning about textAppearance attribute and I don't understand the sintaxis that uses ?. I perfectly understand when we use this sintaxis:
android:textAppearance="@android:style/TextAppearance.Material.Headline"

But I don't understand when we use this sintaxis:
?android:attr/textAppearanceLarge

What are the differences between these two ways of defining the textAppearance?

Using @android/style is understandable because we reference a style resource, but why is there this other way of referencing a style?


Solution

  • You can check the official doc:

    A style attribute resource allows you to reference the value of an attribute in the currently-applied theme. Referencing a style attribute allows you to customize the look of UI elements by styling them to match standard variations supplied by the current theme, instead of supplying a hard-coded value. Referencing a style attribute essentially says, "use the style that is defined by this attribute, in the current theme."

    To reference a style attribute, the name syntax is almost identical to the normal resource format, but instead of the at-symbol (@), use a question-mark (?), and the resource type portion is optional.

    You can use a style like:

    android:textAppearance="@style/TextAppearance.MaterialComponents.Subtitle1"
    

    In this way you are using:

    <style name="TextAppearance.MaterialComponents.Subtitle1" parent=".....">
      ...
    </style>
    

    You can use an attribute defined in your app theme:

     android:textAppearance="?attr/textAppearanceSubtitle1"
    

    In your app theme:

    <style name="AppTheme" parent="Theme.MaterialComponents.*">
       <item name="textAppearanceSubtitle1">@style/TextAppearance.MaterialComponents.Subtitle1</item>
    </style>
    

    The same behavior is used for other resources. For example the colors:

    <style name="AppTheme" parent="Theme.MaterialComponents.*">
       <item name="colorPrimary">@color/....</item>
    </style>
    

    In a view you can use:

    app:backgroundTint="?attr/colorPrimary"