I shared this answer here , but since it has its own conversational flow, I feel that it also matters here.
There is no solution to this problem, but it worked for my use. The problem is that the constructor "View (context, attrs, defStyle)" does not refer to the actual style, it wants to get an attribute. So we will:
- Define Attribute
- Create the style you want to use
- Apply style for this attribute in our topic
- Create new instances of our view with this attribute.
In 'res / values ββ/attrs.xml' define a new attribute:
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="customTextViewStyle" format="reference"/> ... </resources>
In res / values ββ/styles.xml "I'm going to create a style that I want to use in my custom TextView
<style name="CustomTextView"> <item name="android:textSize">18sp</item> <item name="android:textColor">@color/white</item> <item name="android:paddingLeft">14dp</item> </style>
In 'res / values ββ/themes.xml' or 'res / values ββ/styles.xml' change the theme for your application / action and add the following style:
<resources> <style name="AppBaseTheme" parent="android:Theme.Light"> <item name="@attr/customTextViewStyle">@style/CustomTextView</item> </style> ... </resources>
Finally, in your custom TextView, you can now use the constructor with the attribute, and it will get your style
public class CustomTextView extends TextView { public CustomTextView(Context context) { super(context, null, R.attr.customTextView); } }
It is worth noting that I have repeatedly used customTextView in different variants and different places, but it does not require that the name of the view match the style or attribute or anything else. In addition, this method should work with any custom view, not just TextViews.