为 MainActivity 创建一个 ListView holder

Making a ListView holder for MainActivity

我让我的列表视图在 MainActivity 上显示它,布局设置为具有新 Person 对象的 3 个 TextView 属性。

我以前的代码可以运行,但滚动速度很慢,所以我研究了使用 Holder 模式进行优化。然而,当我试图实现这个时,我在 TextView personID=(TextView) view.findViewById(R.id.person_field1)

行得到 NullPointerException

listView 设置为 MainActivity 上的 ListView,我需要人员对象显示在 MainActivity 中的此视图上。

主要活动class:

public void onButtonClick() 
{
   //put the persons objects on the listView within MainActivity
   listView.setAdapter(new personAdapter(MainActivity.this, R.layout.list_layout, 
                        personList));
}

class personAdapter extends ArrayAdapter<Person>
{
    private LayoutInflater layoutInflator;

    public personAdapter(Context context, int resource, List<Person> p) {
        super(context, resource, p);
        layoutInflator = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        Holder holder = null;
        Person p = getItem(position);

        if (view == null) {
            layoutInflator.inflate(R.layout.list_layout, null);  

            //getting null pointer exceptions here
            TextView personID = (TextView) view.findViewById(R.id.person_field1);
            TextView personFName = (TextView) view.findViewById(R.id.person_field2);
            TextView personLName = (TextView) view.findViewById(R.id.person_field3);

            holder = new Holder(personID, personFName, personLName);

            view.setTag(holder);
        }
        else {
            holder = (Holder) view.getTag();
        }

        holder.stop.setText(person.getID());
        holder.location.setText(person.getFName());
        holder.time.setText(person.getLName()); 
        return view;
    }
}

static class Holder 
{
    public TextView id;
    public TextView FName;
    public TextView LName;

    public Holder(TextView id, TextView FName, TextView LName) {
        this.id = id;
        this.FName = FName;
        this.LName = LName;
    }
}

只需添加对您的视图的引用:

view = layoutInflator.inflate(R.layout.list_layout, null);

因为确实有null 注意检查view == null,然后view从未初始化 试试这个

view = layoutInflator.inflate(R.layout.list_layout, null);  

view 为空,您甚至正在检查它:

if (view == null) { ...
}

您缺少的是将膨胀的布局分配给 view

view = layoutInflator.inflate(R.layout.list_layout, null);