Search code examples
androidreferenceonitemclick

Get reference to an object within a ListView


Up front: This is my first attempt at an Android app. I'm in that strange place of not knowing what to search for to find the answer to my question.

What I have accomplished is:

  • Created a custom class myCustomClass with properties of 'title' and 'youTubeUrl'
  • Created an ArrayList<myCustomClass>
  • Added multiple elements to ArrayList<myCustomClass>
  • Created a custom ArrayAdapter and attached it to the the arraylist.
  • Added an onItemClickListener to the custom ArrayAdapter.

All of that works good. I would like to show the title in the ListView and then when the user clicks the list view item, I'd like to get a reference to the youtubeUrl property.

Here's what I have for the adapter code:

MyListAdapter myListAdapter = new MyListAdapter(this, R.layout.my_list, elements);
myList.setAdapter(myListAdapter);
myList.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String item = ((TextView)view).getText().toString();
        Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
    }
});
myListAdapter.notifyDataSetChanged();

Thanks for your help.


Solution

  • You can use the position property in onItemClick to go back to your data source and find the relevant item. From there you should be able to retrieve the Url.