Artem M
Artem M

Reputation: 1036

Android: Get textColor attribute from a certain style defined in styles.xml

I have two styles defined in styles.xml and styles.xml(v21). They both include a textAppearance attribute that links to a certain default android text style.

styles.xml

<style name="NotificationTitle">
    <item name="android:textAppearance">
        @android:style/TextAppearance.StatusBar.EventContent.Title
    </item>
</style>

styles.xml (v21)

<style name="NotificationTitle">
    <item name="android:textAppearance">
        @android:style/TextAppearance.Material.Notification.Title
    </item>
</style>

These default styles contain some text attributes: textColor, textSize, etc:

...
<style name="TextAppearance.Material.Notification.Title">
    <item name="textColor">@color/primary_text_default_material_light</item>
    <item name="textSize">@dimen/notification_title_text_size</item>
</style>
...

I need to get this textColor programmatically by the name of my custom style (NotificationTitle in the example). I tried to obtain it using obtainStyledAttributes, but it don't return. What should I do?

int resultColor;
int[] attrs = {android.R.attr.textColor};
TypedArray ta = context.obtainStyledAttributes(R.style.NotificationText, attrs);

if (ta != null) {
    resultColor = ta.getColor(0, Color.TRANSPARENT);
    ta.recycle();
}

Upvotes: 1

Views: 1924

Answers (1)

TheTallWitch
TheTallWitch

Reputation: 414

Sorry if I'm a bit late with an answer but I tried your code with a bit of modification, I changed the style to this:

<style name="NotificationTitle" parent="TextAppearance.AppCompat.Notification.Title"/>
<style name="NotificationText" parent="TextAppearance.AppCompat.Notification.Line2"/>

and everything worked well with the rest of your code (and didn't need the v21 for the styles now that I used AppCompat)

I hope this helps.

Upvotes: 1

Related Questions