What is the equivalent of "android:fontFamily="sans-serif-light" in Java code?

Waza_Be picture Waza_Be · Jan 15, 2013 · Viewed 62.7k times · Source

My question is quite simple:

In every of my textview, I am currently using the attribute

android:fontFamily="sans-serif-light"

to provide a gorgeous look on post HC devices.

Unfortunately, this doesn't work with every widget and for my Spinners, I need to overwrite the Adapter.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //You can use the new tf here.

    if(convertView == null || convertView.getTag() == null) {
        // new view - populate 
        convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
        convertView.setTag(new Object());
    }

    CheckedTextView spinner_text=(CheckedTextView) convertView.findViewById(android.R.id.text1);
    //Typeface should be set here...
    return spinner_text;
    }
}

So, is there a way to get exactly the same result by code?

PS: No, I don't want to put a typeface in asset folder, I just want to use system one.

Answer

saschoar picture saschoar · Jan 15, 2013

It should be possible with setTypeface() and Typeface.create():

convertView.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));

See Docs:

Create a typeface object given a family name, and option style information. If null is passed for the name, then the "default" font will be chosen. The resulting typeface object can be queried (getStyle()) to discover what its "real" style characteristics are.

Note that excessively using Typeface.create() is bad for your memory, as stated in this comment. The suggested Hashtable is a good solution, but you have to modify it a little since you don't create your typeface from an asset.