Friday, April 15, 2011

Call getItem instead of parent.getItemAtPosition

On your list item click listener, usually you will need to get the item clicked. You can do it with:

News news = (News) parent.getItemAtPosition(position);

However, I don't recommend that, mainly because of the cast. If you change the adapter to operate on items of different type, the compiler will not catch the error.

Instead, access the adapter directly.

News news = adapter.getItem(position);

This is possible only if you make the adapter return the correct item type instead of Object:

public News getItem(int position) {
return list == null || position >= list.items.size()? null: list.items.get(position);

(for long-time Java user, you may not have noticed that that was possible starting Java 5.)

No comments:

Post a Comment