I have got implemented a custom BaseAdapter for displaying Todos. The Todos contain different attributes. Now the problem is, that when I add new Todos to it and scroll down (so that the ListView entries cannot been seen anymore) the text of the existing Todos is reset to test.
I appreciate every help from you, thanks!
Custom BaseAdapter:
public class TodosArrayAdapter extends BaseAdapter {
private List<Todo> todos;
private LayoutInflater inflater;
public TodosArrayAdapter(List<Todo> todos, LayoutInflater inflater) {
if (todos == null || inflater == null) {
throw new IllegalArgumentException();
}
this.todos = todos;
this.inflater = inflater;
}
public void addTodo(Todo todo) {
this.todos.add(todo);
notifyDataSetChanged();
}
public void removeTodo(Todo todo) {
this.todos.remove(todo);
notifyDataSetChanged();
}
@Override
public int getCount() {
return todos.size();
}
@Override
public Object getItem(int position) {
return todos.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final TodoHolder holder;
if (convertView == null) {
holder = new TodoHolder();
holder.ref = position;
convertView = inflater.inflate(R.layout.todolistitem_layout, null);
holder.tvTitle = (EditText) convertView.findViewById(R.id.tvTitle);
convertView.setTag(holder);
} else {
holder = (TodoHolder) convertView.getTag();
}
Todo todo = (Todo) getItem(position);
holder.tvTitle.setText(todo.getTitle());
holder.tvTitle.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
todos.get(holder.ref).setTitle(s.toString());
}
});
return convertView;
}
static class TodoHolder {
int ref;
EditText tvTitle;
}
}
The Todos:
public class Todo {
private String title;
private String description;
private Date date;
public Todo(String title, String description, Date date) {
this.title = title;
this.description = description;
this.date = date;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public Date getDate() {
return date;
}
public void setTitle(String title) {
this.title = title;
}
}
Initializing the adapter:
ArrayList<Todo> todos = new ArrayList<>();
todos.add(new Todo("first", "first description", new Date()));
todos.add(new Todo("second", "second description", new Date()));
todos.add(new Todo("third", "third description", new Date()));
todosAdapter = new TodosArrayAdapter(todos, this.getLayoutInflater());
listView = (ListView) findViewById(R.id.todos);
listView.setAdapter(todosAdapter);
Adding new Todos from a button:
todosAdapter.addTodo(new Todo("test", "test description", new Date()));
Aucun commentaire:
Enregistrer un commentaire