2012-06-28 29 views
4

我的應用程序運行android冰淇淋三明治後,在字體文件夾中導入roboto.ttf和roboto-bold.ttf字體並設置四個字體與這些字體後,是在滾動列表視圖時非常(很)很慢。 有誰知道一種優化性能的方法嗎?有沒有提高速度的技巧和訣竅?導入資產/字體文件夾中的roboto字體後,我的應用程序滾動很糟糕

我澄清它插入幾行代碼之前,很順利:

Typeface roboto = Typeface.createFromAsset(activity.getAssets(), "fonts/Roboto-Regular.ttf"); 
    Typeface robotobold = Typeface.createFromAsset(activity.getAssets(), "fonts/Roboto-Bold.ttf"); 
    nome.setTypeface(robotobold); 
    mq.setTypeface(roboto); 
    citta.setTypeface(roboto); 
    prezzo.setTypeface(roboto); 
    descrizione.setTypeface(roboto); 

我添加的類別可以用字體緩存的幫助:

public class TypefaceCache { 
    private final HashMap<String, Typeface> map; 
    private Context con; 
    public TypefaceCache(Context con) { 
       map = new HashMap<String, Typeface>(); 
       this.con = con; 
    } 


    public Typeface getTypeface(String file) { 
    Typeface result = map.get(file); 
    if (result == null) { 
     result = Typeface.createFromAsset(con.getAssets(), file); 
     map.put(file, result); 
    } 
    return result; 
    } 
} 

我所說的階級和字體通過

TypefaceCache typecache = new TypefaceCache(activity); 
    Typeface roboto = typecache.getTypeface("fonts/Roboto-Regular.ttf"); 

但結果是一樣的...

+0

你什麼時候打這個代碼? – Eric

+0

我創建了一個typefaceCache對象,你可以從我的帖子中查看,我創建了一個字體對象,並立即將字體放在textview中。我把這個代碼放在一個asynctask中,從開始的活動開始 – Release

回答

0

這是我的解決方案: 在我啓動UI我插入類變量的AsyncTask

private final HashMap<String, Typeface> map; 

,然後我initialyze它通過類的構造函數

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

我實現了在類中加載我的字體的方法:

private Typeface getTypeface(String file, Context context) { 
    Typeface result = map.get(file); 
    if (result == null) { 
     result = Typeface.createFromAsset(context.getAssets(), file); 
     map.put(file, result); 
    } 
    return result; 
} 

然後,無論何時我想在asynctask中,我添加我最喜歡的字體,我加載在我的textviews上,並且非常流暢。 謝謝大家

4

您可以嘗試緩存您的Typeface

public class TypefaceCache { 
    private final HashMap<String, Typeface> map = 
     new HashMap<String, Typeface>(); 

    private Typeface getTypeface(String file, Context context) { 
    Typeface result = map.get(file); 
    if (result == null) { 
     result = Typeface.createFromAsset(context.getAssets(), file); 
     map.put(file, result); 
    } 
    return result; 
    } 
} 
+0

我在你的課程中編輯了我的文章,謝謝你的回答,但是它不會更好 – Release

1

我不久前有這個問題,解決方法是設置類,靜態的,就像它在這個blog定律描述;

public class TypefaceSingleton { 
    private static TypefaceSingleton instance = new TypefaceSingleton(); 
    private TypefaceSingleton() {} 

    public static TypefaceSingleton getInstance() { 
     return instance; 
    } 
    public Typeface getTypeface() { 
     return Typeface.createFromAsset(ThinkNearApp.getContext().getResources().getAssets(), "fonts/Roboto-Bold.ttf"); 
    } 
} 
+0

你能更好地解釋我如何繼續嗎? – Release

相關問題