1

Currently, am setting the background of a TextView using code like this:

textView.setBackgroundResource(R.drawable.rect_with_border_grey);

I then came to know about dimens.xml usage and how you can set through that file. Is it possible to set the background through ? i.e. I want to do the above code line through XML. Any help please?

I wouldn't do this using layout xml file as @Opiatefuchs pointed out (in the comment below). B'cos, this textview's background will change depending on the user setting in the App dynamically.

Jean
  • 2,611
  • 8
  • 35
  • 60
  • Just add attribute for TextView style:"@drawable/rect_with_border_grey" – Amsheer Feb 05 '15 at 14:11
  • what about to set the textViews background in the layout xml? dimens.xml is just, like the name said, for dimensions not style. To set a style for a view, there is a styles.xml – Opiatefuchs Feb 05 '15 at 14:11
  • @Opiatefuchs I wouldn't do it with layout xml b'cos, this textview's background will change depending on the user setting in the App dynamically – Jean Feb 05 '15 at 14:16
  • if You want to set it programmatically, it is not possible like this with a style. This what You have done seems to be the only way, or You could create a custome view. For that, look here: Blundells answer http://stackoverflow.com/questions/11723881/android-set-view-style-programatically – Opiatefuchs Feb 05 '15 at 14:22

4 Answers4

1

Make a style like

<style name="MyTextStyle">
 Do everything you want to do with your TextView here.
</style>

and then assign that style to your textview in xml like this

style="@style/MyTextStyle"

It will work.

shivamDev31
  • 469
  • 1
  • 8
  • 23
0

dimen.xml is only use for giving dimension only. for setting background you need to do it with either layout xml file or from java.

Its up-to the requirement of setting background.

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
0

I finally found that you cannot set the background of a TextView via element (i.e. XML) in Android. You need to use layout XML. But, in my case, I cannot use layout since the background will change dynamically based on user choice in the App.

Jean
  • 2,611
  • 8
  • 35
  • 60
-1

create dimens.xml file like this:

<resources>
    <dimen name="paddingTop">10dp</dimen>
    <dimen name="paddingRight">20dp</dimen>
    ...
</resources>

then use it in your layout xml files like this:

android:layout_marginTop="@dimen/paddingTop"
android:layout_marginTop="@dimen/paddingRight"
Miki Franko
  • 687
  • 3
  • 7