Set style for TextView programmatically

后端 未结 12 1650
南方客
南方客 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:13

    The accepted answer was great solution for me. The only thing to add is about inflate() method.

    In accepted answer all android:layout_* parameters will not be applied.

    The reason is no way to adjust it, cause null was passed as ViewGroup parent.

    You can use it like this:

    View view = inflater.inflate(R.layout.view, parent, false);

    and the parent is the ViewGroup, from where you like to adjust android:layout_*.

    In this case, all relative properties will be set.

    Hope it'll be useful for someone.

    0 讨论(0)
  • 2020-11-22 10:17

    I have only tested with EditText but you can use the method

    public void setBackgroundResource (int resid)

    to apply a style defined in an XML file.

    Sine this method belongs to View I believe it will work with any UI element.

    regards.

    0 讨论(0)
  • 2020-11-22 10:18

    You can pass a ContextThemeWrapper to the constructor like this:

    TextView myText = new TextView(new ContextThemeWrapper(MyActivity.this, R.style.my_style));
    
    0 讨论(0)
  • 2020-11-22 10:23

    You can set the style in the constructor (but styles can not be dynamically changed/set).

    View(Context, AttributeSet, int) (the int is an attribute in the current theme that contains a reference to a style)

    Answer from Romain Guy

    reference

    0 讨论(0)
  • 2020-11-22 10:23

    Dynamically changing styles is not supported (yet). You have to set the style before the view gets created, via XML.

    0 讨论(0)
  • 2020-11-22 10:24

    You can create a generic style and re-use it on multiple textviews like the one below:

    textView.setTextAppearance(this, R.style.MyTextStyle);
    

    Edit: this refers to Context

    0 讨论(0)
提交回复
热议问题