SmokeTester
SmokeTester

Reputation: 21

How to set text size for app in one place?

I want to be able to set the text size on an application wide basis. So I will need to be able to access the value in code and xml.

I tried putting the size in my dimens.xml as follows...

 <item name="text_size_small" type="dimen" format="float">15.0</item>

But I was unable to re-use this in xml i.e...

android:textSize="@dimen/text_size"

Gives an exception...

android.view.InflateException: Binary XML file line #29: Error inflating class RadioButton

Also I think I would need to specify the units i.e 'sp' in this case.

So is there a way to do it?

If not, i will probably have to set all text size's that need setting, programmatically. Hopefully someone knows a better way.

Upvotes: 1

Views: 94

Answers (3)

mehmetunlu
mehmetunlu

Reputation: 239

You must define own textview style.

@styles

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">

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

</style>

<style name="CMTextView" parent="android:style/Widget.TextView">

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

</style>

@dimens

<dimen name="text_size">18sp</dimen>

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157487

inside dimens.xml, you can use the <dimen item, and specify the unit:

<dimen name="text_size_small">15sp</dimen>

to access it programmatically, you

textview.setTextSize(getResources().getDimension(R.dimen.text_size_small), TypedValue.COMPLEX_UNIT_PX);

in dimens the size is already scaled for the unit, so you don't need to apply the conversion again, hence the TypedValue.COMPLEX_UNIT_PX

Upvotes: 1

David
David

Reputation: 1026

In your dimens.xml specify your like this

<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="text_size_small">15sp</dimen>
</resources>

In your layout use this
android:textSize="@dimen/text_size_small"

If you want to set this programtically, try like this
textview.setTextSize(getResources().getDimension(R.dimen.text_size_small));

Upvotes: 0

Related Questions