How to create listview with dynamic contents in android
Hi, Today I will show how to create a simple
listview with dynamic list items.
steps
1 create a activity XML file with a listview,
2 then update the object in the java class
ListView ll= ListView findViewById R.id.listView1 ;
3 Now create a string array and add some elements
Let us create 3 elements called shop1,shop2 and shop3
String array = "Shop1","Shop2","Shop3" ;
4 Now, to add dynamic elements into the list, let us
create a ArrayList. This is a template class, so we have
to mension the template type, since we are using only
text in the textview, I will add the String in the template
ArrayList String lst = new ArrayList String Arrays.asList array ;
I created a object called lst using the array
5 To add dynamic contents , use add method.
for example, I added one dynamic element called Shop4.
lst.add "Shop4" ;
you can add any thing dynamically using for or any other loop with DB access.
6 It is time to update the list view.
final ArrayAdapter String adapter = new ArrayAdapter String this,
android.R.layout.simple_list_item_1, lst ;
Create a ArrayAdapter, this takes the argument
1st argument -Activity instance I used this pointer, for this instance
2nd argument -the layout of the list view, there is an inbuild layout in
android for the list, it is android.R.layout.simple_list_item_1
3ed argument -the arraylist lst
7 Now set the view
ll.setAdapter adapter ;
8 To get which element was selected, we use OnItemClickListener
ll.setOnItemClickListener new OnItemClickListener
@Override
public void onItemClick AdapterView ? arg0, View arg1, int arg2,
long arg3
// TODO Auto-generated method stub
TextView txt= TextView arg1;
System.out.println txt.getText .toString ;
;
The view argument in the onItemClick represents the textview that is clicked.
first convert into TextView.
TextView txt= TextView arg1;
Then using getText find the text.