Android ListView项目被重复

时间:2015-07-25 03:06:05

标签: android listview android-adapter

我有一个列表视图,使用自定义适配器填充信息,显示树状结构。然而,父母'级别评论总是重复。这是我的自定义适配器的代码:

class CommentListAdapter extends BaseAdapter {

        private LayoutInflater layoutInflater;

        public CommentListAdapter(CommentActivity commentActivity){
            layoutInflater = (LayoutInflater) commentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return commentFeed.getCommentCount();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        class listViewHolder {
            RelativeLayout spacerRelLayout;
            TextView authorText;
            TextView bodyText;
            TextView timeText;

            listViewHolder(View v) {
                spacerRelLayout = (RelativeLayout) v.findViewById(R.id.spacerLayout);
                authorText = (TextView) v.findViewById(R.id.authorTextComment);
                bodyText = (TextView) v.findViewById(R.id.commentTextView);
                timeText = (TextView) v.findViewById(R.id.timeTextComment);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View listItem = convertView;
            listViewHolder holder;

            if (listItem == null) {
                listItem = layoutInflater.inflate(R.layout.comment_item_layout, parent, false);
                holder = new listViewHolder(listItem);
                listItem.setTag(holder);
            } else {
                holder = (listViewHolder) listItem.getTag();
            }

            holder.bodyText.setText(Html.fromHtml(commentFeed.getComment(position).getBody()));
            holder.timeText.setText(commentFeed.getComment(position).getTime());
            holder.authorText.setText(commentFeed.getComment(position).getAuthor());
            holder.spacerRelLayout.getLayoutParams().width = commentFeed.getComment(position).getLevel() *10;
            holder.spacerRelLayout.invalidate();

            return listItem;

        }
    }

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

getItem应如下所示:

@Override
public Object getItem(int position) {
    return commentFeed.getComment(position);
}

然后在你的getView内执行此操作:

Comment comment = (Comment) getItem(position);
holder.bodyText.setText(Html.fromHtml(comment.getBody()));
// etc..