Setting styles of programmatically added Views

送分小仙女□ 提交于 2019-12-01 18:06:30

You can pass a style defined inside styles.xml as an argument of a View constructor. So considering your example, you would have 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 custom radio button style defined in styles.xml

As for me, it has been successfully solved just by that way:

Activity.java

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

...

    { 
        RadioButton rb = (RadioButton) inflater.inflate(R.layout.radio_butt, null);
        rb.setText(this_currency_option);
        rb.setTextColor(context.getResources().getColor(R.color.colorWhite));
        rb.setId(100 + i);
        radioGroup.addView(rb);
    }

radio_butt.xml

<?xml version="1.0" encoding="utf-8"?>
<RadioButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="14sp"
    android:textColor="@color/colorWhite"
    android:theme="@style/MyRadioButtonStyle"/>

slyles.xml

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="colorControlNormal">@color/colorAlfaWhite</item>
    <item name="colorControlActivated">@color/colorWhite</item>
</style>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!