Frage

I would like to set by default layout_width = wrap_content and layout_height = wrap content to all my TextViews. So I tried to modify the theme file with:

<item name="android:textViewStyle">@style/TextViewStyle</item>  

 <style name="TextViewStyle" parent="@android:style/Widget.TextView">
    <item name = "android:layout_width">wrap_content</item>
    <item name = "android:layout_height">wrap_content</item>
</style>

But if I set a TextView without layout_width or without layout_height, the app stops at execution time.

Can it be done the way I proppose? With big projects it could save a lot of xml "useless" lines.

War es hilfreich?

Lösung

Unfortunately it is not possible to set layout attributes (layout_*) from a theme (see Layout Parameters documentation and this answer from an Android framework engineer). You can however set the layout attributes in a style and let each element reference the style like this:

<Button style="@style/ButtonBig" android:text="my text" />

where ButtonBig is defined like this:

<style name="ButtonBig" parent="android:Widget.Holo.Light.Button">
    <item name="android:textSize">20sp</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">100dp</item>        
</style>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top