Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialZainal Azfar
931 Pointshow to get the position number only when I click on a listview item?
How do i get the position number.eg: when i click on item number 5, it will return me an int 4. So i only want this when i click the item
2 Answers
Jahath Inyang
8,182 PointsOne way to go about this is to set an onItemClickListener on the listview instance to get the value.
Lets say you have a listview on your xml and the id is list_item.
//First declare a listview object
protected ListView mListView;
//Next bind mListView with your listview in the xml (This will be in your onCreate)
mListView = (ListView) findViewById(R.id.list_item);
//Finally, set an onItemClickListener
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// the position of the item clicked will come in as the 3rd parameter of the onItemClick callback
// which is 'position'. You can use the value to do whatever you want
}
});
The position you are looking for is the 'position' parameter in the onItemClick!
*** Sorry for the code wrapping into other lines. I am still trying to figure out how to do line breaks for code here.
Jahath Inyang
8,182 PointsThanks Daniel! If you don't mind me asking, how did you change the syntax highlighting?
Daniel Hartin
18,106 PointsDaniel Hartin
18,106 PointsHi Jahath
I just changed your syntax highlighting to make it more clear and changed it to an answer, good job looks correct to me!
Daniel