How to programmatically set style attribute in a view

前端 未结 11 2131
北恋
北恋 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 07:00

    I made a helper interface for this using the holder pattern.

    public interface StyleHolder {
        void applyStyle(V view);
    }
    

    Now for every style you want to use pragmatically just implement the interface, for example:

    public class ButtonStyleHolder implements StyleHolder

    Declare a stylable in your attrs.xml, the styleable for this example is:

    
        
        
        
    
    

    Here is the style declared in styles.xml:

    
    

    And finally the implementation of the style holder:

    Button btn = new Button(context);    
    StyleHolder

    I found this very helpful as it can be easily reused and keeps the code clean and verbose, i would recommend using this only as a local variable so we can allow the garbage collector to do its job once we're done with setting all the styles.

提交回复
热议问题