android set style in code

2018-12-31 14:14发布

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

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

however, when i do this, the text view does not appear to take the style (I verified the style by setting it on a static object).

I've also tried using myText.setTextAppearance(MyActivity.this, R.style.my_style) but it also doesn't work

10条回答
临风纵饮
2楼-- · 2018-12-31 14:38

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

查看更多
大哥的爱人
3楼-- · 2018-12-31 14:44

You can pass a ContextThemeWrapper to the constructor like this:

TextView myText = new TextView(new ContextThemeWrapper(MyActivity.this, R.style.my_style));
查看更多
心情的温度
4楼-- · 2018-12-31 14:44

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.

查看更多
裙下三千臣
5楼-- · 2018-12-31 14:46

When using custom views that may use style inheritance (or event styleable attributes), you have to modify the second constructor in order not to lose the style. This worked for me, without needing to use setTextAppearence():

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs, attrs.getStyleAttribute());
}
查看更多
何处买醉
6楼-- · 2018-12-31 14:48

Parameter int defStyleAttr does not specifies the style. From the Android documentation:

defStyleAttr - An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

To setup the style in View constructor we have 2 possible solutions:

  1. With use of ContextThemeWrapper:

    ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.your_style);
    TextView textView = new TextView(wrappedContext, null, 0);
    
  2. With four-argument constructor (available starting from LOLLIPOP):

    TextView textView = new TextView(yourContext, null, 0, R.style.your_style);
    

Key thing for both solutions - defStyleAttr parameter should be 0 to apply our style to the view.

查看更多
明月照影归
7楼-- · 2018-12-31 14:51

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

View(Context, AttributeSet, int) (the int is a style resource)

Answer from Romain Guy

reference

查看更多
登录 后发表回答