Wednesday, June 9, 2010

Something simple. Get text from a ListView.

Perhaps this topic is considered too simple for most people, which is why there aren't more postings about it. But, it seems like a useful thing to know. Specifically, when you are using a ListView with the android.R.layout.simple_list_item_1 view, how the heck do you get the text from the item clicked in the OnItemClickListener class?

It is pretty simple. The second parameter of the onItemClick is a View that contains just the item that was clicked. (Or tapped, whatever.) If you used Eclipse to automagically generate the callback method for you, the variable will be named "arg1", which is what we will assume for this example.

Inside of the onItemClick method, you can figure out the text using the following code :

String s = ((TextView)arg1.findViewById(android.R.id.text1)).getText().toString();


Pretty simple, huh? But, the code doesn't quite explain itself. So, I'll take a stab at it.

A ListView is exactly what the name says. It is a list of views. When you create the ArrayAdapter that you will use to display the data, you also tell the ArrayAdapter what view it should use. In our case, we chose "android.R.layout.simple_list_item_1" so we could use a simple array for the data. What we are doing is referencing a very simple layout that only displays a single line of text. I am sure if you Google around you can find the XML definition.

Inside the layout is a single definition. It is a TextView named "text1". Since it is a built-in layout, we will find the layout information under "android.R", instead of just "R" where our layout definitions show up.

So, by executing findViewById() on the view that was clicked, and passed in as "arg1", we can get the text that the user clicked on.

Pretty simple huh?