How to extract the text from the selected item on the listView
The other answers look good, but I thought I'd wrap everything
up into one complete answer.
There are multiple ways
to achieve this and it also depends on whether you are getting text from simple listView
or from Custom ListView(with custom_list_item.xml).
For Simple ListView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String text = lv.get(position).tostring().trim();//first method
final String text = ((TextView)view).getText();// second method
}});
For Custom ListView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView textView = (TextView) view.findViewById(R.id.list_content);
//where list_content is the id of TextView in listview_item.xml
}});
Problem with others Answers
@Android Killer
string Casting is missing.
@Rishi
doesn't give detail about using R.id.list_content
Hello I'm using a CustomListView with Registered Context Menu. In this case the way to access a item inside a custom list row will be:
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.add:
TextView textView = (TextView) info.targetView.findViewById(R.id.yourItem);
String text = textView.getText().toString();
Toast.makeText(getApplicationContext(), "Selected " + text, Toast.LENGTH_LONG).show();
default:
return super.onContextItemSelected(item);
}
}
Where R.id.yourItem is the textView inside the custom Row
PS: It's my first post, Hope it helps ;-)
Use this:
String selectedFromList = (String) (lv.getItemAtPosition(position));
Whatever the datatype you are having in your list, cast accordingly.
Hope it will help. :)
For this you need to write the following:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView textView = (TextView) view.findViewById(R.id.list_content);
String text = lv.get(position).toString().trim();
System.out.println("Chosen Country = : " + text);
}});