5

为了在我的ListActivity中提供自定义字体,我编写了一个类CustomAdapter,根据此示例BaseAdapter延伸here活动缓慢过渡:LogCat中的多个“初始化充气状态”

然而,由于所描述的,我写的getView()方法类似如下:

public View getView(int position, View convertView, ViewGroup parent){ 
    String gameName = gameNames[position]; // gameName ist the String[] of the Custom Adapter 

    TextView tv = new TextView(context); 
    tv.setText(gameName); 
    tv.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/gulim.ttf")); 

    return tv; 
} 

这按预期工作。唯一令人不安的是大约需要三到四秒钟,直到列表出现(在这种情况下这是一个很长的时间)。然而,在ListActivity我设置onItemClickListener就像这样:

private void setOnItemClickListener(){ 
    getListView().setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, int pos, long id){ 
      onClickEntryButton(((TextView) view).getText().toString()); 
     } 
    }); 
} 

private void onClickEntryButton(String gameName){ 
    Intent intent = new Intent(this, GameActivity.class); 
    intent.putExtra("gameName", gameName); 
    startActivity(intent); 
    finish(); 
} 

现在在ListItem点击时,直到GameActivity打开需要更多的时间。这个Activity只是几个TextView s充满了从SQLite数据库中获取的信息。在这里,我为每个TextView设置一个自定义字体。即使屏幕变黑2-3秒(出现应用程序崩溃),然后出现新的Activity。这不会发生从应用程序中的其他地方访问Activity

在两种情况下 - 访问ListActivity和访问GameActivityListActivity - 一对夫妇的

“szipinf - 初始化膨胀状态”

消息出现在logcat中。他们在这方面的含义是什么?将onItemClickListener设置为我的CustomAdaptergetView()方法会更好吗?有些东西似乎真的抑制了转换,但我无法弄清楚什么,因为没有什么大的计算或处理(事实上,在SQLite数据库中,每个5个字段只有两个条目)?

编辑 如果需要或希望,当然我可以提供更多的代码。

回答

3

我有完全相同的问题,你的问题给我答案!

我仍然不知道确切的根本原因,但这个isuue是因为在我的情况下多次从资产中读取自定义字体。 如果我的屏幕中有10个小部件,并且每个小部件都使用自定义字体,则Android会每次从资产中加载它。这不仅导致我的活动转换变慢,而且在玩过多个时间后也导致崩溃。

所以我为我的字体创建了一个缓存,以避免每次从资产中获取字体。

我加入这个代码我的工具类中:

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

public static final String ASSET_PATH="assetPath"; 

public static Typeface getFont(Context c, String assetPath) { 
    synchronized (cache) { 
     if (!cache.containsKey(assetPath)) { 
      try { 
       Typeface t =(Typeface.createFromAsset(c.getAssets(), 
         "fonts/arial.ttf")); 
       cache.put(assetPath, t); 
      } catch (Exception e) { 
       return null; 
      } 
     } 
     return cache.get(assetPath); 
    } 
} 

我创建我的自定义类在setTypeface

public class MyButton extends Button { 

public MyButton(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
} 

public MyButton(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

public MyButton(Context context) { 
    super(context); 
} 

@Override 
public void setTypeface(Typeface tf) { 

    super.setTypeface(Util.getFont(getContext(), Util.ASSET_PATH)); 
} 

} 

变量assetPath可以用来在运行时提供不同势字体

编辑Here是自定义typefaceManager我已创建为一个库,使其更多通用的。