Waza_Be Waza_Be - 1 year ago 153
Android Question

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

My question is quite simple:

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


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.

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download