Setting styles of programmatically added Views

前端 未结 2 580
野性不改
野性不改 2021-01-18 07:00

In my code, I add input elements like radioButtons, checkboxes etc to my Layout programmatically. The problem is, that the style of those elements is not the default style t

相关标签:
2条回答
  • 2021-01-18 07:52

    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

    0 讨论(0)
  • 2021-01-18 08:01

    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>
    
    0 讨论(0)
提交回复
热议问题