Ayleanna
Ayleanna

Reputation: 193

Can I use variables in XML for Android?

Instead of using this following line for each textview:

android:textSize="40sp"

Am I able to replace 40sp with a variable?

As a side question, I've been recommended to use SP units as it goes by user defined settings. Is this a best practice?

Upvotes: 9

Views: 15349

Answers (3)

Leon Lucardie
Leon Lucardie

Reputation: 9730

No, it's not possible to use code based variables in XML files. However, you can use styles for this.

Example:

<style name="MyTvStyle">
  <item name="android:textSize">40sp</item>
</style>

Then apply it like this:

<TextView style="@style/MyTvStyle" ... />

A code based approach is also possible. If the TextViews have their android:id attribute defined you can retrieve them in the code with the findViewById method.

Example:

int[] id_array = {
    R.id.textview1, R.id.textview2, R.id.textview3 //Put all the id's of your textviews here
}

for(int i : id_array) { //Loop trough all the id's and retrieve the Textview associated with it.
    TextView textview = (TextView)findViewById(i);
    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,40); //Set the text size to 40sp
}

And yes it's always better to use sp instead of normal pixel values. Since sp will scale with device size and user settings.

Upvotes: 4

CommonsWare
CommonsWare

Reputation: 1006724

Am I able to replace 40sp with a variable?

You can either use a dimension resource (e.g., android:textSize="@dimen/someSize"), or use a style that does this (per AlexN's answer), or set the size at runtime via setTextSize().

I've been recommended to use SP units as it goes by user defined settings. Is this a best practice?

On newer versions of Android, the user can change the base font size via the Settings application. By using sp for units, your font sizes will scale along with the base font size. If you use other units (e.g., dp), your font size will remain the same regardless of what the user has in Settings. It is impossible to say whether any given use of sp is a "best practice" or not -- I am sure that there are cases where allowing the font size to change would be a bad thing. By default, though, sp is probably the right starting point.

Upvotes: 9

AlexN
AlexN

Reputation: 2554

As I know, using SP is a really good practice for Text Size. And according to your first question - I think we cannot use variable, however, there is a better way. Check it out - http://developer.android.com/guide/topics/ui/themes.html

So if you'll define a style, you can declare your Views in XML like <TextView android:id = "@+id/myId" style = "@style/myStyle"/> And this style will incapsulate all parameters you want to set to your textViews on that screen.

Upvotes: 3

Related Questions