6

我在 xml 文件中有一些数据,将其放在 /res/values/mydata.xml 中。我想用自定义字体在列表视图中显示数据。模拟器中的一切都很棒,但在真实设备中(使用带有 android 4.0.3 的三星 Galaxy Tab 10.1 2)滚动列表视图时速度太慢。实际上它适用于默认字体,但设置自定义字体时会出现问题。

这是我的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;
    }
}

这是什么问题?是关于我的设备的吗?任何解决方案都可以帮助我。谢谢

4

1 回答 1

16

你的问题是那一行:

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

您应该在适配器的构造函数中这样做一次,创建font一个成员变量,而不仅仅是使用该变量来调用setTypeface(font)您的TextView.

getView()应防止该方法中的重载。

另请阅读有关适配器的 convertView / ViewHolder 模式,这也将给您带来性能提升。

更新示例:

private class MyAdapter extends ArrayAdapter<String> {
    Typeface font;

    public MyAdapter(Context context, int resource, int textViewResourceId,
            String[] string) {
        super(context, resource, textViewResourceId, string);
        font = Typeface.createFromAsset(context.getAssets(),"myFont.ttf");
    }

    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 {
            tv.setTypeface(font);
        } catch (Exception e) {
            Log.d("Alireza", e.getMessage().toString());
        }

        tv.setText(item[position]);
        return row;
    }
}
于 2012-10-25T21:28:29.803 回答