Liza  Tjaica
Liza Tjaica

Reputation: 593

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

Upvotes: 5

Views: 8518

Answers (2)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22647

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.

Upvotes: 10

Pratik Sharma
Pratik Sharma

Reputation: 13415

Prepare such files first :

res/values-ldpi/dimens.xml
res/values-mdpi/dimens.xml
res/values-hdpi/dimens.xml

Then declare resource values for different files:

<!-- in values-ldpi/dimens.xml -->
<dimen name="mytextSize">30dp</dimen>

and

<!-- in values-mdpi/dimens.xml -->
<dimen name="mytextSize">20dp</dimen>

Then, use this way in your style :

<item name="android:textSize">@dimen/mytextSize</item>

Upvotes: 1

Related Questions