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我已創建爲一個庫,使其更多通用的。