Set style for TextView programmatically

后端 未结 12 1798
南方客
南方客 2020-11-22 09:47

I\'m trying to use the TextView constructor with style like this:

TextView myText = new TextView(MyActivity.this, null, R.style.my_style);
         


        
12条回答
  •  悲&欢浪女
    2020-11-22 10:33

    I met the problem too, and I found the way to set style programatically. Maybe you all need it, So I update there.

    The third param of View constructor accepts a type of attr in your theme as the source code below:

    public TextView(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.textViewStyle);
    }
    

    So you must pass a type of R.attr.** rather than R.style.**

    In my codes, I did following steps:

    First, customize a customized attr to be used by themes in attr.xml.

    
    

    Second, specific your style in your used theme in style.xml.

     
    
    

    At the end, use it!

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

    the view created programatically will use the specified style in your theme.

    You can have a try, and hope it can work for you perfectly.

提交回复
热议问题