Question

I have created a custom listview with two TextViews with ID text1 and text2. text1 shows a place and text2 shows a description. At first when I implemented the onListItemClicked method and fed the data into a toast it showed the data in the first textview which is the place in text1. Now wanted to extract from text 2 so found an answered suggested by someone here on S/O but it now only extracts data from the text2 of the first list item and not where I have clicked. Any idea how to get data dynamically? Not familiar with data sources so all data is in 2arrays,or is there no way and I have to get data at that position from the second array that holds descriptions?
Some code from the custom list class:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    View parentView =(View)v.getParent();
    String text;
    text=((TextView) parentView.findViewById(R.id.text2)).getText().toString();
        Toast.makeText(this, text+" !here(description)",
        Toast.LENGTH_LONG).show();
}
Was it helpful?

Solution

The View v in onListItemClick represents the ViewGroup for the row you've clicked. Therefore, you don't need the getParent method. Change your code as follows:

@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
    String text;
    text=((TextView) v.findViewById(R.id.text2)).getText().toString();
    Toast.makeText(this, text+" !here(description)", Toast.LENGTH_LONG).show();
}

The parentView, as you have it, would refer to the entire ListView's view hierarchy. Within that, there would be multiple Views that each contain a TextView with id == R.id.text2. I would guess that findViewById would just grab the first one it finds in that hierarchy, which is why it's always returning the value from the first row.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top