0

I'm trying to dynamically create a TextView and then set a style which I previously defined in XML.

This is the XML which I defined in styles.xml:

<style name="box_area">
    <item name="android:layout_width">30dp</item>
    <item name="android:layout_height">30dp</item>
    <item name="android:background">@android:color/holo_red_dark</item>
</style>

Java Code:

TextView tv = new TextView(this, null, R.style.box_area);

I don't know which is the reason, but the style is not being applied. Thank you

Pietro
  • 29
  • 8
  • 1
    Possible duplicate of [How to programmatically set style attribute in a view](https://stackoverflow.com/questions/2016249/how-to-programmatically-set-style-attribute-in-a-view) – Bö macht Blau Aug 12 '18 at 17:50
  • Is the background set right or not? –  Aug 12 '18 at 17:59
  • The third parameter in a `View` constructor is _not_ for an `R.style`. It's for an `R.attr`. – Mike M. Aug 12 '18 at 23:19

4 Answers4

1

Add parent="android:Widget.TextView" for the given style.Then it should work fine.

Code after editing should look like this

<style name="box_area" parent="android:Widget.TextView>
<item name="android:layout_width">30dp</item>
<item name="android:layout_height">30dp</item>
<item name="android:background">@android:color/holo_red_dark</item>

Hope it helps.

Anubhav Gupta
  • 2,492
  • 14
  • 27
0

Add below line into your textview's property, it will solve your problem.

style="@style/box_area"

Something like below

<TextView
style="@style/box_area"
........
/>
Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
0

In your style.xml add parent

android:Widget.TextView

to implement style like this code:

<style name="box_area” parent="android:Widget.TextView">
    <item name="android:textColor">#F00</item>
    <item name="android:textStyle">bold</item>
</style>
Aseem Sharma
  • 1,673
  • 12
  • 19
0

The height and width of View will be processed only by Layout Params which you define for Simple View Component's parent layout. If you are creating your view programmatically, you must get instance of your component's parent layout either by findViewById or instantiating your parent ViewGroup. Then assign the LayoutParam as a parameter at same time you call addView to add text view to it's parent.

also, you can add view to it's parent, then measure it by calling measure method.

Mahdi Rajabi
  • 582
  • 1
  • 4
  • 11