Custom Font in Android Listview

Custom font for Android listview


Here is the custom adapter class and the constructor

class CustomAdapter extends ArrayAdapter<CharSequence>{

Context context;
int layoutResourceId;
CharSequence data[] = null;
Typeface tf;

public CustomAdapter(Context context, int layoutResourceId, CharSequence[] data, String FONT ) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
tf = Typeface.createFromAsset(context.getAssets(), FONT);
}

Put the font you want to use in your assets folder and fill your listview like this:

listAdapter = new CustomAdapter(this, R.layout.custom_list_text, R.array.abra_hotel, "name_of_font.ttf");

custom font in android ListView

You can't do it that way because the text view resource you pass to the ArrayAdapter is inflated each time it is used.

You need to create your own adapter and provide your own view.

An example for your adapter could be

public class MyAdapter extends BaseAdapter {

private List<Object> objects; // obviously don't use object, use whatever you really want
private final Context context;

public CamAdapter(Context context, List<Object> objects) {
this.context = context;
this.objects = objects;
}

@Override
public int getCount() {
return objects.size();
}

@Override
public Object getItem(int position) {
return objects.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

Object obj = objects.get(position);

TextView tv = new TextView(context);
tv.setText(obj.toString()); // use whatever method you want for the label
// set whatever typeface you want here as well
return tv;
}

}

And then you could set that as such

ListView lv = new ListView(this);
lv.setAdapter(new MyAdapter(objs));

Hopefully that should get you going.



Related Topics



Leave a reply



Submit