I have a custom android view class which amongst other things is going to be drawing a lot of text directly into the canvas supplied to its onDraw override.
What I'd like to do is have a attribute which could be set to something like "?android:attr/textAppearanceLarge" and pick up the regular text settings without further styling.
In my custom view's attrs.xml, I have
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView" >
...
<attr name="textAppearance" format="reference" />
...
</declare-styleable>
</resources>
and then in CustomView.java
final int[] bogus = new int[] { android.R.attr.textColor, android.R.attr.textSize, android.R.attr.typeface, android.R.attr.textStyle, android.R.attr.fontFamily };
final int ap = styledAttributes.getResourceId(com.test.R.styleable.MyView_textAppearance, -1);
final TypedArray textAppearance = ap != -1 ? context.obtainStyledAttributes(ap, bogus) : null;
if (textAppearance != null) {
for (int i = 0; i < textAppearance.getIndexCount(); i++) {
int attr = textAppearance.getIndex(i);
switch (attr) {
case android.R.attr.textColor: textColor = textAppearance.getColor(attr, textColor); break;
case android.R.attr.textSize: textSize = textAppearance.getDimensionPixelSize(attr, textSize); break;
case android.R.attr.typeface: typefaceIndex = textAppearance.getInt(attr, typefaceIndex); break;
case android.R.attr.textStyle: textStyle = textAppearance.getInt(attr, textStyle); break;
case android.R.attr.fontFamily: fontFamily = textAppearance.getString(attr); break;
}
}
textAppearance.recycle();
}
I've tried all sorts of variations on the switch variable, on the case constants etc and I never end up getting anything even remotely useful.
What am I doing wrong here?
I know this is an old question but just stumbled into this issue and this solution works for me:
in attrs.xml
<resources>
<declare-styleable name="CustomView">
....
<attr name="textAppearance" format="reference" />
</declare-styleable>
</resources>
in CustomView.java
textAppearance = a.getResourceId(R.styleable.CustomView_textAppearance, -1);
TextViewCompat.setTextAppearance(textView, textAppearance);
then in activity.xml
<CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:textAppearance="?android:attr/textAppearanceMedium"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With