To dynammically add new elements into listview we need a Edittext(etAddItem) to input the item/element, a Button(btnAdd) for adding item to the list, and a listview which shows elements in a vertical scrolling manner.
etAddItem = (EditText)findViewById(R.id.etAddItem);
btnAdd = (Button)findViewById(R.id.btnAdd);
listView = (ListView)findViewById(R.id.lvList);
btnAdd(Button) onClickListner, when user clicks on add button element/item is added to the arraylist.
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
arrayList.add(etAddItem.getText().toString());
adapter.notifyDataSetChanged();
etAddItem.setText(null);
}
});
finally, adapter works as a communication channel between Listview and ArrayList.
arrayList = new ArrayList();
adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);
// Here, you set the data in your ListView
listView.setAdapter(adapter);
0 Comment(s)