Can anyone explain or suggest a tutorial to dynamically create a ListView in android?
Here are my requirements:
First, you have to add a ListView, an EditText and a button into your activity_main.xml.
Now, in your ActivityMain:
private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTxt = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
list = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
// Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
// and the array that contains the data
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);
// Here, you set the data in your ListView
list.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// this line adds the data of your EditText and puts in your array
arrayList.add(editTxt.getText().toString());
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
}
});
}
This works for me, I hope I helped you