Android change ListView font

Shahbaz Pothiawala picture Shahbaz Pothiawala · Aug 18, 2013 · Viewed 8.5k times · Source

Seems to be a simple question, but since I am new to Android development I have very little idea about Android ListViews. Following is the code I have used for a ListView in my project.

/*Listview code starts*/
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayList<String> planetList = new ArrayList<String>();  
planetList.addAll( Arrays.asList(values) );
listAdapter = new ArrayAdapter<String>(this, R.layout.list1, values);
mainListView.setAdapter(listAdapter); 
mainListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
                int itemPosition = position;
                String  itemValue    = (String) mainListView.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(),
                        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                .show();
        }
});
/*Listview code ends*/

I wish to change the Font of my ListView text. How do I do that? Read everywhere to use a custom Adapter, but did not understand. Can anyone help me with the code?

Answer

Ye Lin Aung picture Ye Lin Aung · Aug 18, 2013

If you want to go by the way with creating a new ArrayAdapter and access to the items inside the ListView by overriding the getView() method. Please have a look at Adapter#getView .. Here and Here are good tutorials about customizing the ListView.

Sample custom ArrayAdapter will be like this.

public class CustomArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;

    public CustomArrayAdapter(Context context, String[] values) {
        super(context, R.layout.list_mobile, values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.list_mobile, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);

        // Customization to your textView here
        textView.setText("Hello");
        textView.setTypeface(my_custom_typeface);
        textView.setTextSize(20);


        return rowView;
    }
}

And you can create a new CustomArrayAdapter by like this.

CustomArrayAdapter my_adapter = new CustomArrayAdapter();
setListAdapter(my_adapter);

Ref : Android TextView Methods.