ListView在下拉時出現空指標錯誤
阿新 • • 發佈:2019-01-25
原因出在adapter的getView方法中
原先的寫法:
@Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; ViewHolder holder = null; if(convertView == null) { holder = new ViewHolder(); LayoutInflater inflater = getLayoutInflater(); view = inflater.inflate(R.layout.list_cell, null); holder.tvTitle = (TextView) view.findViewById(R.id.tv_title); holder.tvDetail = (TextView) view.findViewById(R.id.tv_content); holder.tvComment = (TextView) view.findViewById(R.id.tv_comment); } else { view = convertView; } holder.tvTitle.setText(newsList.get(position).getTitle()); holder.tvDetail.setText(newsList.get(position).getDetail()); holder.tvComment.setText(newsList.get(position).getComment() + "跟帖"); return view; }
改正後寫法:
出現空指標的原因應該是ListView滑動後,原先的寫法holder內的變數(tvTitle)不能找到了。@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView == null) { holder = new ViewHolder(); LayoutInflater inflater = getLayoutInflater(); convertView = inflater.inflate(R.layout.list_cell, null); holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title); holder.tvDetail = (TextView) convertView.findViewById(R.id.tv_content); holder.tvComment = (TextView) convertView.findViewById(R.id.tv_comment); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.tvTitle.setText(newsList.get(position).getTitle()); holder.tvDetail.setText(newsList.get(position).getDetail()); holder.tvComment.setText(newsList.get(position).getComment() + "跟帖"); return convertView; }