Custom font for text viewing in ArrayAdapter

I am trying to change the font of a TextView in my ArrayAdapter . The chantelli_antiqua.ttf font is located in the resource folder.

Here is my Java code:

 listItemAdapter = new ArrayAdapter<MenuItem>(this, R.layout.listitem, menuItems); Typeface font = Typeface.createFromAsset(getAssets(), "chantelli_antiqua.ttf"); TextView v = (TextView)listItemAdapter.getView(0, null, null); v.setTypeface(font); 

xml for listitem layout:

 <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="30sp" /> 

I am sure that the problem lies in the Adapter.getView(int, View, ViewGroup) . I just don't understand what to pass as variables and tried null . But that does not do what I would like.

How to change TextView font in Adapter to custom font?

Update

Following Pixie's suggestion, I created a MenuItemAdapter that extends ArrayAdapter<MenuItem> :

 public class MenuItemAdapter extends ArrayAdapter<MenuItem> { private Typeface font; public MenuItemAdapter(Context context, int textViewResourceId, List<MenuItem> objects) { super(context, textViewResourceId, objects); font = Typeface.createFromAsset(context.getAssets(), "chantelli_antiqua.ttf"); } @Override public View getView(int position, View view, ViewGroup viewGroup) { ((TextView)view).setTypeface(font); return super.getView(position, view, viewGroup); } } 

And changed my java code to:

 listItemAdapter = new MenuItemAdapter(this, R.layout.listitem, menuItems); 

But now my application crashes after onCreate ListActivity , but before I hit the breakpoint in getView(...) , I still could not figure out why. Any suggestion? Strike>

Update2

Changed the code for getView (...):

 @Override public View getView(int position, View view, ViewGroup viewGroup) { View v = super.getView(position, view, viewGroup); ((TextView)v).setTypeface(font); return v; } 

and it works. :)

+7
source share
2 answers

You should not call the getView() method of your adapter. ListView does this for you. You must extend the ArrayAdapter class and override the getView() method. In this method, you must inflate a new view or reuse convertView and set the font for that view.

+2
source

I think the problem is return super.getView(position, view, viewGroup); at the end of the getView () method. I think it should be like that

  @Override public View getView(int position, View view, ViewGroup viewGroup) { TextView tv = ((TextView)view).setTypeface(font); tv.setText(<String> getItem()); return tv; } 

Please note that this code is an example. I have not tried this now, but I did a customARAdapter before, and it was something like this.
Here is a tutorial that describes how to create a custom array adapter.

+2
source

All Articles