Custom Styles for Programmatically Added Views

In my code, I programmatically add input elements like radioButtons, checkboxes, etc. The problem is that the style of these elements is not the default style that you would get when you add, say, radioButton via xml. (It looks really white and almost transparent on the white background of the application. It’s a bit like transparency) Also, the EditText elements that I add have the same style, and if you enter something into them, the text is too big and a bit overlaps the text string. Therefore, I assume that it all boils down to somehow giving these elements the default style of how they look when they are defined through xml.

A sample of my code is as follows:

RadioGroup radioGroup = new RadioGroup(mContext); radioGroup.setLayoutParams(fullWidthWrapHeight); for (int i = 0; i < arg0.getOptions().size(); i++){ RadioButton radioButton = new RadioButton(mContext, null); radioButton.setPadding(padding16dp , padding8dp, padding16dp, padding8dp); radioButton.setText(arg0.getOptions().get(i).getText()); radioButton.setLayoutParams(wrapBoth); radioButton.setGravity(Gravity.CENTER_HORIZONTAL); radioButton.setTextAppearance(mContext, R.style.Default_Text); radioGroup.addView(radioButton); } 

My target lvl API is 21 (Lollipop)

+6
source share
1 answer

You can pass the style defined inside styles.xml as an argument to the View constructor. Therefore, given your example, you need to call:

 RadioButton radioButton = new RadioButton(mContext, null, R.attr.radioButtonStyle); 

then add custom attribute inside attrs.xml

 <attr name="radioButtonStyle" format="reference" /> 

and inside your application theme in styles.xml add

 <item name="radioButtonStyle">@style/YourRadioButtonStyle</item> 

YourRadioButtonStyle is a custom radio button style defined in styles.xml

+12
source

Source: https://habr.com/ru/post/981280/


All Articles