我正在使用Android Studio上的自定义适配器执行待办事项列表,但我尝试添加项目,它只是停止运行。
public class MainActivity extends AppCompatActivity {
private ListView mToDoList;
private EditText mTask;
private Button mAddButton;
private TarefaAdapter adapter;
private List<Tasks> tasks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToDoList = (ListView) findViewById(R.id.todo_listView);
mTask = (EditText) findViewById(R.id.editText);
mAddButton = (Button) findViewById(R.id.button);
tasks = new ArrayList<Tasks>();
adapter = new TarefaAdapter(tasks, this);
mToDoList.setAdapter(adapter);
mAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = mTask.getText().toString();
Tasks task = new Tasks();
task.setName(content);
tasks.add(task);
adapter.notifyDataSetChanged();
}
});
如果没有&#39; adapter.notifyDataSetChanged();&#39;应用程序不会停止运行,但也不会将对象添加到列表中:(
这是适配器:
public class TarefaAdapter extends BaseAdapter{
private final List<Tasks> tarefas;
private final Activity act;
public TarefaAdapter(List<Tasks> tarefas, Activity act) {
this.tarefas = tarefas;
this.act = act;
}
@Override
public int getCount() {
return tarefas.size();
}
@Override
public Object getItem(int position) {
return tarefas.get(id);
}
@Override
public long getItemId(int position) {
return tarefas.get(position).getId();
}
@Override
public View getView(int position, View v, ViewGroup parent) {
View view = act.getLayoutInflater().inflate(R.layout.item, null);
Tasks tarefa = tarefas.get(position);
TextView nome = (TextView) view.findViewById(R.id.textView);
nome.setText(tarefa.getName());
return view;
}
}