4

我的应用程序运行android冰淇淋三明治,在字体文件夹中导入roboto.ttf和roboto-bold.ttf字体并使用这些字体设置四个文本视图之后,滚动列表视图时非常(非常)慢。有谁知道优化性能的方法?是否有任何提高速度的提示和技巧?

我澄清在插入这些代码行之前它非常顺利:

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

但结果是一样的......

4

3 回答 3

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;
  }
}
于 2012-06-28T02:55:54.953 回答
1

不久前我遇到了这个问题,解决方案是将类设置为静态,就像在这个博客中描述的一样;

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"); 
    } 
}
于 2012-06-28T11:18:14.870 回答
0

这是我的解决方案:在我启动 ui 的异步任务中,我插入类变量

private final HashMap<String, Typeface> map;

然后我通过类构造函数初始化它

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

然后,每当我想在异步任务中,我添加我最喜欢的字体,我加载到我的文本视图上,一切都非常顺利。谢谢你们

于 2012-06-28T11:33:06.600 回答