且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据添加到 listView 的自定义 BaseAdapter - Android

更新时间:2023-10-13 23:06:17

你试试这个:

public class Comment {
String username;
String content;
String number;
 }

类适配器:

public class CommentAdapter extends BaseAdapter {
private List<Comment> listComment;
private Context context;

public CommentAdapter(List<Comment> listComment, Context context) {
    super();
    this.listComment = listComment;
    this.context = context;
}

@Override
public int getCount() {

    return listComment.size();
}

@Override
public Comment getItem(int position) {
    return listComment.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = mInflater.inflate(R.layout.comment_item, null);
    }

    final TextView textViewUsername = (TextView) v
            .findViewById(R.id.comment_Username);
    final TextView textViewNumber = (TextView) v
            .findViewById(R.id.comment_number);
    final TextView textViewContent = (TextView) v
            .findViewById(R.id.comment_Content);

    final String username = listComment.get(position).getUsername();
    final String number= listComment.get(position).getNumber();
    String content = listComment.get(position).getContent();

    textViewUsername.setText(username);
    textViewNumber.setText(number);

    textViewContent.setText(content);
    return v;
}

}

当您需要向列表添加新评论时.只需创建新评论并添加到listComment(listComment.add(newComment)),然后调用adapter.notifyDataSetChanged();

When you need to add new comment to list. just create new Comment and add to listComment(listComment.add(newComment)), after that, call adapter.notifyDataSetChanged();