Method 1 - Create TextInputLayout programmatically with wrapping Context with android. view. ContextThemeWrapper and use. TextInputLayout layout = new TextInputLayout(new ContextThemeWrapper(getContext(), R.
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);
AND
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.
For a new Button/TextView:
Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);
For an existing instance:
mMyButton.setTextAppearance(this, R.style.button_enabled);
For Image or layouts:
Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With