Viewholder不适用于自定义适配器

时间:2014-12-08 13:24:32

标签: android android-listview android-viewholder

以下是用于listview的自定义列表适配器的代码。如果我注释掉" not null"我的代码中的令牌,没有我的视图持有者。有人可以帮我解决我在这里遇到的问题吗?

public View getView(int i, View view, ViewGroup viewGroup) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.eachlist, viewGroup, false);

        if (this.subject==null && this.percentage==null && this.happen==null && this.missed==null) {

            Log.d("null cha","error");
            subject = (TextView) row.findViewById(R.id.subjectname);
            happen=(TextView)row.findViewById(R.id.attended);
            missed=(TextView)row.findViewById(R.id.missed);
            percentage=(TextView)row.findViewById(R.id.Attendance);

            new viewholder(subject,happen,missed,percentage);
        }
        else {

            subject=viewholder.subject;
            happen=viewholder.happen;
            missed=viewholder.missed;
            percentage=viewholder.percentage;

        }

        subject.setText(list.get(i).subject);
        happen.setText(String.valueOf(list.get(i).happened));
        missed.setText(String.valueOf(list.get(i).missed));
        percentage.setText(String.valueOf(list.get(i).percentage));

        return row;
    }
    static class viewholder{
        static TextView subject;
        static TextView happen;

        static TextView missed;
        static TextView percentage;

        viewholder(TextView subject,TextView happen,TextView missed,TextView percentage){
            this.subject=subject;
            this.happen=happen;
            this.missed=missed;
            this.percentage=percentage;

        }


    }

1 个答案:

答案 0 :(得分:0)

您应该检查系统(也称为convertView)作为参数提供的视图是否为空,并且仅在这种情况下使您的布局膨胀。

if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.eachlist, viewGroup, false);
        subject = (TextView) view.findViewById(R.id.subjectname);
        happen=(TextView)view.findViewById(R.id.attended);
        missed=(TextView)view.findViewById(R.id.missed);
        percentage=(TextView)view.findViewById(R.id.Attendance);
        ViewHolder v new ViewHolder(subject,happen,missed,percentage);
        view.setTag(v);
    }  else {
        ViewHolder v = (ViewHolder) view.getTag();
        subject=v.subject;
        happen=v.happen;
        missed=v.missed;
        percentage=v.percentage;

    }

   ..
  return view;
 }
相关问题