user2881473
user2881473

Reputation: 15

Adding Custom Font in a Listview

Please pardon my ignorance, I'm a total newbie to programming. I'm trying to add a custom font to this android app with a listview. I copied this code from an answer to a similar question asked here: Custom font for Android listview

 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);
} 

But I'm struggling figuring out where to put this line of code:

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

No matter where I try placing it, it throws an error...

Here is my MainActivity class:

 public class MainActivity extends Activity {



// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";

// List items 
ListView list;
BinderData adapter = null;
List<HashMap<String,String>> weatherDataCollection;




@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    try {


        DocumentBuilderFactory docBuilderFactory = 
 DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (getAssets().open("weatherdata.xml"));

        weatherDataCollection = new ArrayList<HashMap<String,String>>();

        // normalize text representation
        doc.getDocumentElement ().normalize ();

        NodeList weatherList = doc.getElementsByTagName("weatherdata");

        HashMap<String,String> map = null;

        for (int i = 0; i < weatherList.getLength(); i++) {

               map = new HashMap<String,String>(); 

               Node firstWeatherNode = weatherList.item(i);

                if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){

                    Element firstWeatherElement = (Element)firstWeatherNode;
                    //-------
                    NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID);
                    Element firstIdElement = (Element)idList.item(0);
                    NodeList textIdList = firstIdElement.getChildNodes();
                    //--id
                    map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim());

                    //2.-------
                    NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_CITY);
                    Element firstCityElement = (Element)cityList.item(0);
                    NodeList textCityList = firstCityElement.getChildNodes();
                    //--city
                    map.put(KEY_CITY, ((Node)textCityList.item(0)).getNodeValue().trim());

                    //3.-------
                    NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_TEMP_C);
                    Element firstTempElement = (Element)tempList.item(0);
                    NodeList textTempList = firstTempElement.getChildNodes();
                    //--city
                    map.put(KEY_TEMP_C, ((Node)textTempList.item(0)).getNodeValue().trim());

                    //4.-------
                    NodeList condList = firstWeatherElement.getElementsByTagName(KEY_CONDN);
                    Element firstCondElement = (Element)condList.item(0);
                    NodeList textCondList = firstCondElement.getChildNodes();
                    //--city
                    map.put(KEY_CONDN, ((Node)textCondList.item(0)).getNodeValue().trim());

                    //5.-------
                    NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED);
                    Element firstSpeedElement = (Element)speedList.item(0);
                    NodeList textSpeedList = firstSpeedElement.getChildNodes();
                    //--city
                    map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim());

                    //6.-------
                    NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON);
                    Element firstIconElement = (Element)iconList.item(0);
                    NodeList textIconList = firstIconElement.getChildNodes();
                    //--city
                    map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim());

                    //Add to the Arraylist
                    weatherDataCollection.add(map);
            }       
        }


        BinderData bindingData = new BinderData(this,weatherDataCollection);

        // list.setCacheColorHint(Color.TRANSPARENT);




        list = (ListView) findViewById(R.id.list);

        Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>");

        list.setAdapter(bindingData);

        Log.i("AFTER", "<<------------- After SetAdapter-------------->>");

        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                switch (position) {
                case 0:
                 Intent newActivity0 = new Intent(MainActivity.this, 
 SecondActivity.class);     
                 startActivity(newActivity0);
                break;}

                switch (position) {
                case 1:
                 Intent newActivity1 = new Intent(MainActivity.this, 
 ThirdActivity.class);     
                 startActivity(newActivity1);
                break; }

                switch (position) {
                case 2:
                 Intent newActivity2 = new Intent(MainActivity.this, 
 FourthActivity.class);     
                 startActivity(newActivity2);
                break; }

                switch (position) {
                case 3:
                 Intent newActivity3 = new Intent(MainActivity.this, 
 FifthActivity.class);     
                 startActivity(newActivity3);
                break; }

                switch (position) {
                case 4:
                 Intent newActivity4 = new Intent(MainActivity.this, 
 SixthActivity.class);     
                 startActivity(newActivity4);
                break; }

                switch (position) {
                case 5:
                 Intent newActivity5 = new Intent(MainActivity.this, 
 SeventhActivity.class);     
                 startActivity(newActivity5);
                break; }

                switch (position) {
                case 6:
                 Intent newActivity6 = new Intent(MainActivity.this, 
 EighthActivity.class);     
                 startActivity(newActivity6);
                break; }

                switch (position) {
                case 7:
                 Intent newActivity7 = new Intent(MainActivity.this, 
 NinthActivity.class);     
                 startActivity(newActivity7);
                break; }

                switch (position) {
                case 8:
                 Intent newActivity8 = new Intent(MainActivity.this, 
 TenthActivity.class);     
                 startActivity(newActivity8);
                break; }

                switch (position) {
                case 9:
                 Intent newActivity9 = new Intent(MainActivity.this,  
 EleventhActivity.class);     
                 startActivity(newActivity9);
                break; }




        }});

    }

    catch (IOException ex) {
        Log.e("Error", ex.getMessage());
    }
    catch (Exception ex) {
        Log.e("Error", "Loading exception");
    }
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;


}


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);
} 

}

}

BinderData class:

 public class BinderData extends BaseAdapter {



// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";


LayoutInflater inflater;
ImageView thumb_image;
List<HashMap<String,String>> weatherDataCollection;
ViewHolder holder;
public BinderData() {
    // TODO Auto-generated constructor stub
}

public BinderData(Activity act, List<HashMap<String,String>> map) {

    this.weatherDataCollection = map;

    inflater = (LayoutInflater) act
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


public int getCount() {
    // TODO Auto-generated method stub //       
            return idlist.size();
    return weatherDataCollection.size();
}

public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

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

    View vi=convertView;
    if(convertView==null){

      vi = inflater.inflate(R.layout.list_row, null);
      holder = new ViewHolder();

      holder.tvCity = (TextView)vi.findViewById(R.id.tvCity); // city name
      holder.tvWeather = (TextView)vi.findViewById(R.id.tvCondition); // city weather 
 overview
      holder.tvTemperature =  (TextView)vi.findViewById(R.id.tvTemp); // city temperature
      holder.tvWeatherImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image

      vi.setTag(holder);
    }
    else{

        holder = (ViewHolder)vi.getTag();
    }

      // Setting all values in listview

      holder.tvCity.setText(weatherDataCollection.get(position).get(KEY_CITY));
      holder.tvWeather.setText(weatherDataCollection.get(position).get(KEY_CONDN));
      holder.tvTemperature.setText(weatherDataCollection.get(position).get(KEY_TEMP_C));

      //Setting an image
      String uri = "drawable/"+ weatherDataCollection.get(position).get(KEY_ICON);
      int imageResource = 
 vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, 
 vi.getContext().getApplicationContext().getPackageName());
      Drawable image = vi.getContext().getResources().getDrawable(imageResource);
      holder.tvWeatherImage.setImageDrawable(image);

      return vi;
}

/*
 * 
 * */
static class ViewHolder{

    TextView tvCity;
    TextView tvTemperature;
    TextView tvWeather;
    ImageView tvWeatherImage;
}



 }

ListAdapter Class:

 class CustomListAdapter extends BaseAdapter{

LayoutInflater inflater=null;

int count=0;
String[] List;
Context context;
public CustomListAdapter(Context c,String[] list){

    List = list;
    count =  list.length;
    context=c;

    inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

    // TODO Auto-generated constructor stub

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return count;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int postion) {
    // TODO Auto-generated method stub
    return postion;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View view = convertView;
    view = inflater.inflate(R.layout.list_row, null);
    TextView TextofList = (TextView) view.findViewById(R.id.tvCity);
    float textsize = (float) 15.0;
    TextofList.setTextSize(textsize);
    TextofList.setText(List[position]);
    return view;
}

}

Upvotes: 0

Views: 263

Answers (2)

Naveed Ali
Naveed Ali

Reputation: 2619

use this class to customize your list...

  class CustomListAdapter extends BaseAdapter{

    LayoutInflater inflater=null;

    int count=0;
    String[] List;
    Context context;
    public CustomListAdapter(Context c,String[] list){

        List = list;
        count =  list.length;
        context=c;

        inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return count;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int postion) {
        // TODO Auto-generated method stub
        return postion;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View view = convertView;
        view = inflater.inflate(R.layout.row, null);
        TextView TextofList = (TextView) view.findViewById(R.id.tv_list);
        float textsize = 15.0;
                    TextofList.setTextSize(textsize);
                    TextofList.setText(List[position]);
        return view;
    }

}

and also add below given lines to your activity class....

 public class MainActivity extends Activity {
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
          String[] list = {"abc","cde,","add",,"cde,","add",,"cde,","add"};
     ListView listv= (ListView) findViewById(R.id.listview);

 CustomListAdapter adapter = new CustomListAdapter(this,list);
 listv.setAdapter(adapter);  
 }//end of OnCreat()
 }//end of mainactivty

hope this will help you

Upvotes: 1

Sergio Ramirez
Sergio Ramirez

Reputation: 680

You need to create a custom ArrayAdapter. Check this tutoria first then change the font of the items in the adapter.

Upvotes: 0

Related Questions