custom font in android ListView

tiswas picture tiswas · Jan 2, 2011 · Viewed 22.7k times · Source

I'm using a custom font throughout my application (which, incidentally, I've frustratingly found out that you have to apply programmatically by hand to EVERY control!), and I need to apply it to a listview. The problem is that I can't see where I'd set the textview used in the list's font to my custom font (as I never instantiate it - that's all taken care of by the adapter).

What I'd ideally like is to be able to use an adapter like this:

new ArrayAdapter(Context context, TextView textView, List<T> objects)

That way I could do: textView.setTypeface before populating my list. Does anyone know if there's a way to do something along these lines?

Answer

Mois&#233;s Olmedo picture Moisés Olmedo · Nov 15, 2012

If you don't want to create a new class you can override the getView method when creating your Adapter, this is an example of a simpleAdapter with title and subtitle:

Typeface typeBold = Typeface.createFromAsset(getAssets(),"fonts/helveticabold.ttf");
Typeface typeNormal = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf");

SimpleAdapter adapter = new SimpleAdapter(this, items,R.layout.yourLvLayout, new String[]{"title",
    "subtitle" }, new int[] { R.id.rowTitle,
    R.id.rowSubtitle }){
            @Override
        public View getView(int pos, View convertView, ViewGroup parent){
            View v = convertView;
            if(v== null){
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v=vi.inflate(R.layout.yourLvLayout, null);
            }
            TextView tv = (TextView)v.findViewById(R.id.rowTitle);
            tv.setText(items.get(pos).get("title"));
            tv.setTypeface(typeBold);
            TextView tvs = (TextView)v.findViewById(R.id.rowSubtitle);
            tvs.setText(items.get(pos).get("subtitle"));
            tvs.setTypeface(typeNormal);
            return v;
        }


};
listView.setAdapter(adapter);

where items is your ArrayList of Maps

hope that helps