How to set font custom font to Spinner text programmatically?
This is what worked for me (using ideas both from CommonsWare's and gsanllorente's answers):
private static class MySpinnerAdapter extends ArrayAdapter<String> { // Initialise custom font, for example: Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Blambot.otf"); // (In reality I used a manager which caches the Typeface objects) // Typeface font = FontManager.getInstance().getFont(getContext(), BLAMBOT); private MySpinnerAdapter(Context context, int resource, List<String> items) { super(context, resource, items); } // Affects default (closed) state of the spinner @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTypeface(font); return view; } // Affects opened state of the spinner @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getDropDownView(position, convertView, parent); view.setTypeface(font); return view; }}
If you, like me, originally populated the Spinner using ArrayAdapter.createFromResource()
and an array resource (as in Spinner documentation), then you'd use MySpinnerAdapter like this:
MySpinnerAdapter<String> adapter = new MySpinnerAdapter( getContext(), R.layout.view_spinner_item, Arrays.asList(getResources().getStringArray(R.array.my_array)));spinner.setAdapter(adapter);
You would apply the font through your own custom SpinnerAdapter
, in getView()
and getDropDownView()
.
If you implement your Adapter in another file, you can access the "getAssets()" function from the constructor of the Adapter, as you have the Context as a parameter.
public class YourItemAdapter extends ArrayAdapter<String> {int recurso;Typeface tf;public YourItemAdapter(Context _context, int _resource, List<String> _items) { super(_context, _resource, _items); recurso=_resource; tf=Typeface.createFromAsset(_context.getAssets(),"font/digital-7.ttf");}@Overridepublic View getView(int position, View convertView, ViewGroup parent) { //You can use the new tf here. TextView spinner_text=(TextView)findViewById(R.id.text1); spinner_text.setTypeface(tf); }}