2012-10-25 30 views
4

我在xml文件中有一些數據放在/res/values/mydata.xml中。我想用自定義字體在列表視圖中顯示數據。在模擬器中一切都很好,但在真正的設備(使用三星galaxy選項卡10.1 2與Android 4.0.3)時,滾動列表視圖太慢。實際上它使用默認字體效果很好,但設置自定義字體時會出現問題。設置自定義字體時的列表查看速度慢

這是我的Java代碼:

public class ShowFoodCalorie extends ListActivity { 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // reading data from xml file 
    setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, 
      R.id.textView1, getResources().getStringArray(R.array.food_cal))); 
} 
private class MyAdapter extends ArrayAdapter<String> { 
    public MyAdapter(Context context, int resource, int textViewResourceId, 
      String[] string) { 
     super(context, resource, textViewResourceId, string); 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater = (LayoutInflater) 
getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View row = inflater.inflate(R.layout.show_all, parent, false); 
     String[] item = getResources().getStringArray(R.array.food_cal); 
     TextView tv = (TextView) row.findViewById(R.id.textView1); 
     try { 
      Typeface font = Typeface.createFromAsset(getAssets(),"myFont.ttf"); 
      tv.setTypeface(font); 
     } catch (Exception e) { 
      Log.d("Alireza", e.getMessage().toString()); 
     } 

     tv.setText(item[position]); 
     return row; 
    } 
} 

這是什麼問題呢?這是關於我的設備?任何解決方案可以幫助我。 感謝

回答

14

你的問題是該行:

Typeface font = Typeface.createFromAsset(getAssets(),"myFont.ttf"); 

你應該這樣做,一旦在適配器的構造,使font一個成員變量,並不僅僅是使用變量調用setTypeface(font)TextView

應防止在getView()方法中重載。

另外閱讀有關適配器的convertView/ViewHolder模式,這也可以提高性能。

+0

謝謝。它正在工作。並感謝您的意見 – IndieBoy

+0

優秀的答案,謝謝你。 –

+1

下面的鏈接有關於@WarrenFaith建議的convertView/ViewHolder模式的好信息。 [http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/](http://lucasr.org/2012/04/05/performance-tips-for-androids-列表顯示/) – MemoryLeak