4

Is it possible to check what family a Typeface object is using in Android API 8?

I am creating the Typeface on a Paint object like so

//Simplified code, the user actually selects the family and style from a list
Paint paint = new Paint();
paint.setTypeface(Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD));

I would later like to be able to check the family like so

Typeface tf= paint.getTypeface();

if (tf.equals(Typeface.DEFAULT) || tf.equals(Typeface.DEFAULT_BOLD)) {
    //do something
} else if (...) {
    //do something else
} 

This does not work as they are not the same object, I have also tried tf == value but again the same result. The Typeface object does not appear to expose anything useful to help with family detection, is there a workaround for this? I only need to detect the basic Android Typefaces (SERIF, SANS-SERIF, DEFAULT, MONOSPACE etc)

Re0sless
  • 10,678
  • 6
  • 51
  • 66

3 Answers3

5

Not readily. The key to the family is a native_instance int, which is package-private and is not directly exposed, as you can see in the source code.

There are various nasty ways of getting at that information, which may or may not work on all devices and all past/present/future versions of Android.

Perhaps you could create your own wrapper object around Typeface that tracks this information.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1

If you look at the sources, you will see that the default ones are created with style DEFAULT (*), so:

Typeface paintTf = paint.getTypeface();
Typeface.SERIF.equals(Typeface.create(paintTf, Typeface.DEFAULT));

might do the job (here I check is family is serif).

NB: (*) is not true for DEFAULT_BOLD.

0

I recommend you to use font from Resources, so that you can simply compare the type face by equals()

example:

Typeface toCompare = ResourcesCompat.getFont(context, R.font.my_font);
assert tf.equals(toCompare)
SeanCheey
  • 143
  • 1
  • 4