Liza  Tjaica Liza Tjaica - 2 months ago 13
Android Question

Android: Different style (textSize) for different layout sizes

I have made custom style for all text buttons on large screens

<style name="button_large" parent="@android:style/Widget.TextView">
<item name="android:textColor">@color/button_color</item>
<item name="android:textSize">30dp</item>
<item name="android:clickable">true</item>
<item name="android:soundEffectsEnabled">false</item>
</style>


Now i want smaller buttons for normal screen and I add noew style where only android:textSize changed.

<style name="button_normal" parent="@android:style/Widget.TextView">
<item name="android:textColor">@color/button_color</item>
<item name="android:textSize">10dp</item>
<item name="android:clickable">true</item>
<item name="android:soundEffectsEnabled">false</item>
</style>


Is it posible to extract this value and recieve needed value based on screen size? And use only one style.

<item name="android:textSize">value_based_on_screen_size</item>


And in case of large screen it weill be 30 and for normal screen it will be 10

Answer

Yes that's possible. Here's how you might arrange it. In your default values/styles.xml have,

<style name="button" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@color/button_color</item>
    <item name="android:textSize">@dimen/button_text_size</item>
    <item name="android:clickable">true</item>
    <item name="android:soundEffectsEnabled">false</item>
</style>

then create a values/dimens.xml like this,

<resources>
    <dimen name="button_text_size">10sp</dimen>
</resources>

and create a values-large like this,

<resources>
    <dimen name="button_text_size">30sp</dimen>
</resources>

P.s., use sp for fonts. it's just like dp, except that if the user increases the default font size through system settings, your fonts will change accordingly.