设置自定义字体时的慢listview

Ind*_*Boy 5 java android truetype android-layout android-fonts

我在xml文件中有一些数据放在/res/values/mydata.xml中.我想用自定义字体在列表视图中显示数据.在模拟器中一切都很棒但在实际设备中(使用三星galaxy tab 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

War*_*ith 15

你的问题就是那条线:

Typeface font = Typeface.createFromAsset(getAssets(),"myFont.ttf");
Run Code Online (Sandbox Code Playgroud)

你应该在你的适配器的构造函数中执行一次,创建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;
    }
}
Run Code Online (Sandbox Code Playgroud)