Android: Set View Style Programmatically


Answer :

Technically you can apply styles programmatically, with custom views anyway:

private MyRelativeLayout extends RelativeLayout {   public MyRelativeLayout(Context context) {      super(context, null, R.style.LightStyle);   } } 

The one argument constructor is the one used when you instantiate views programmatically.

So chain this constructor to the super that takes a style parameter.

RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton)); 

Or as @Dori pointed out simply:

RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle)); 

Now in Kotlin:

class MyRelativeLayout @JvmOverloads constructor(     context: Context,      attributeSet: AttributeSet? = null,      defStyleAttr: Int = R.style.LightStyle, ) : RelativeLayout(context, attributeSet, defStyleAttr) 

or

 val rl = RelativeLayout(ContextThemeWrapper(activity, R.style.LightStyle)) 

What worked for me:

Button b = new Button(new ContextThemeWrapper(this, R.style.ButtonText), null, 0); 
  • Use a ContextThemeWrapper

AND

  • Use the 3-arguments constructor (won't work without this)

Update: At the time of answering this question (mid 2012, API level 14-15), setting the view programmatically was not an option (even though there were some non-trivial workarounds) whereas this has been made possible after the more recent API releases. See @Blundell's answer for details.

OLD Answer:

You cannot set a view's style programmatically yet, but you may find this thread useful.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable