Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView optimization: Typeface makes listview very laggy

In the last couple of hours I was browsing for some listview optimization but I didn't succeed solving my laggy listview, so from row to row I started to revert my code to earlier and simplier versions to figure out the problem. So I populate a listview with a customadapter containing an imageview and two textviews. After removing the image from the item, my listview was still very slow then guess what: if I remove the custom typeface of the textviews my lagginess is gone. I use the simple Calibri which is a built-in font so I dont get why it slows down my listview. Any suggestion to solve this problem?

//viewHolder.text_tt.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/CALIBRI.TTF")); 
//viewHolder.text_ttd.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/CALIBRI.TTF")); 

viewHolder.text_tt.setText(textNames[position]);
viewHolder.text_ttd.setText("Item " + position);
like image 264
Jani Bela Avatar asked Jan 30 '26 18:01

Jani Bela


2 Answers

The reason is because Creating a Typeface from assets is pretty heavy. I prefer to use a TypefaceCache like so..

public class TypefaceCache {

    private static final Hashtable<String, Typeface> CACHE = new Hashtable<String, Typeface>();

    public static Typeface get(AssetManager manager, String name) {
        synchronized (CACHE) {

            if (!CACHE.containsKey(name)) {
                Typeface t = Typeface.createFromAsset(manager, name);
                CACHE.put(name, t);
            }
            return CACHE.get(name);
        }
    }

}

This way, a Typeface will be created just once and will not need to recreated each time.

Remember to add a check to return the default Typeface in case the name parameter is null or Typeface.createFromAsset returns null.

like image 174
Vinay S Shenoy Avatar answered Feb 02 '26 12:02

Vinay S Shenoy


It might be because you are creating new objects for each of your TextView.

When you repeat the below code,

Typeface.createFromAsset(getActivity().getAssets(), "fonts/CALIBRI.TTF")

it means that you are creating a new object. Instead you should create a single object for your Typeface and have it stored globally and use it across your listview. Creating a new object for every row is not recommended.

let's say something like this,

1)Have a constructor for your adapter, and withtin it create this Typeface object once like this,

Typeface typeface= null;  //global declaration

public void constructorSample()
{
   typeface= Typeface.createFromAsset(getActivity().getAssets(), "fonts/CALIBRI.TTF");
}

And then use it like this,.

viewHolder.text_ttd.setTypeface(typeface);
like image 31
Andro Selva Avatar answered Feb 02 '26 12:02

Andro Selva