滚动时自定义ListView getView()方法nullPointerException

时间:2014-01-14 01:04:57

标签: android android-listview nullpointerexception

我有一个自定义列表视图我正在使用自定义适配器。当应用程序最初打开时,前几个项目会正确显示。但是,当我开始向下滚动时,我在getView()方法中得到一个nullPointerException:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    ListViewItem item = items.get(position);

    View vi = convertView;

    if (item.Type.equals("Homework")) {

        if (convertView == null)
            vi = inflater.inflate(R.layout.item_row_homework, null);

        ImageView imgThumbnail = (ImageView) vi
                .findViewById(R.id.homework_imgThumbnail);
        TextView txtTitle = (TextView) vi
                .findViewById(R.id.homework_txtTitle);
        TextView txtSubTitle = (TextView) vi
                .findViewById(R.id.homework_txtSubTitle);

        imgThumbnail.setImageResource(item.ThumbnailResource);
        txtTitle.setText(item.Title);
        txtSubTitle.setText(item.SubTitle);
    }
    if (item.Type.equals("Study")) {

        if (convertView == null)
            vi = inflater.inflate(R.layout.item_row_study, null);

        ImageView imgThumbnail = (ImageView) vi
                .findViewById(R.id.study_imgThumbnail);
        TextView txtTitle = (TextView) vi
                .findViewById(R.id.study_txtTitle);
        TextView txtSubTitle = (TextView) vi
                .findViewById(R.id.study_txtSubTitle);

        imgThumbnail.setImageResource(item.ThumbnailResource);
        txtTitle.setText(item.Title);
        txtSubTitle.setText(item.SubTitle);
    }
    if (item.Type.equals("Project")) {

        if (convertView == null)
            vi = inflater.inflate(R.layout.item_row_project, null);

        ImageView imgThumbnail = (ImageView) vi
                .findViewById(R.id.project_imgThumbnail);
        TextView txtTitle = (TextView) vi
                .findViewById(R.id.project_txtTitle);
        TextView txtSubTitle = (TextView) vi
                .findViewById(R.id.project_txtSubTitle);

        imgThumbnail.setImageResource(item.ThumbnailResource);
        txtTitle.setText(item.Title);
        txtSubTitle.setText(item.SubTitle);
    }

    return vi;
}

它出现在

行的三个实例中的任何一个中
imgThumbnail.setImageResource(item.ThumbnailResource);

我已经看过其他有关这方面的问题,但还不清楚究竟发生了什么。

感谢。

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试重复使用错误的视图类型。

当您向下滚动时,您可能会收到convertView,该R.layout.item_row_homework是使用position布局创建的,但您必须在"Project"绘制的项目对应不同的类型,比如,View.setTag

尝试使用方法getItemViewType(int position)传递视图类型信息并在重新使用之前进行检查。如果类型不同,您可能需要为新视图充气。

只要您使用自定义适配器,更好的方法是覆盖getViewTypeCount()和{{1}}方法来定义支持的不同视图类型。