Can I use variables in XML for Android?

Instead of using this following line for each text field:

android:textSize="40sp"

Is it possible to replace 40sp with a variable?

As a side issue, I was recommended to use SP blocks, as this depends on user preferences. Is this the best practice?

+5
source share
3 answers

Is it possible to replace 40sp with a variable?

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

I was recommended to use SP blocks, as it depends on user settings. Is this the best practice?

Android "". sp , . (, dp), , . , sp " " . , , . , , sp, , .

+5

, SP - . - , , . - http://developer.android.com/guide/topics/ui/themes.html

, , XML, <TextView android:id = "@+id/myId" style = "@style/myStyle"/> , .

+2

, XML . .

:

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

:

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

. TextViews android:id, findViewById.

:

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

for(int i : id_array) { //Loop trough all the id 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 is always better to use spinstead of the usual pixel values. Because it spwill scale with the size of the device and user settings.

+1
source

All Articles