Android - set TextView TextStyle programmatically?

前端 未结 11 631
南旧
南旧 2020-12-02 05:04

Is there a way to set the textStyle attribute of a TextView programmatically? There doesn\'t appear to be a setTextStyle() method.

11条回答
  •  误落风尘
    2020-12-02 05:37

    This question is asked in a lot of places in a lot of different ways. I originally answered it here but I feel it's relevant in this thread as well (since i ended up here when I was searching for an answer).

    There is no one line solution to this problem, but this worked for my use case. The problem is, the 'View(context, attrs, defStyle)' constructor does not refer to an actual style, it wants an attribute. So, we will:

    1. Define an attribute
    2. Create a style that you want to use
    3. Apply a style for that attribute on our theme
    4. Create new instances of our view with that attribute

    In 'res/values/attrs.xml', define a new attribute:

    
    
        
        ...
        
    

    In res/values/styles.xml' I'm going to create the style I want to use on my custom TextView

    
    

    In 'res/values/themes.xml' or 'res/values/styles.xml', modify the theme for your application / activity and add the following style:

    
        
        ... 
    
    

    Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your style

    public class CustomTextView extends TextView {
    
        public CustomTextView(Context context) {
           super(context, null, R.attr.customTextView);
        }
    }
    

    It's worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews.

提交回复
热议问题