How to programmatically set style attribute in a view

前端 未结 11 2015
北恋
北恋 2020-11-22 06:38

I\'m getting a view from the XML with the code below:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
11条回答
  •  终归单人心
    2020-11-22 06:49

    First of all, you don't need to use a layout inflater to create a simple Button. You can just use:

    button = new Button(context);
    

    If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest:

    button.setTextColor(Color.RED);
    button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    

    The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper for this:

    ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
    button = new Button(newContext);
    

    To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method:

    button.setTextAppearance(context, R.style.MyTextStyle);
    

    This last one cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper. But for text color, size, etc. you can use setTextAppearance.

提交回复
热议问题