I have a custom baseadapter which does some lazy loading of some images, and then inflating the layout so I end up with a listview where I have both image and text in one row.
When the user presses one item of the listview, say for example item 0 (top item), I want to show a dialog box with some specific content. This content depends on the item number - so the content shown for item 0 is not the same as for item 1, and so on.
Here is the getView
method of the custom adapter:
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
if(convertView==null)
{
vi = inflater.inflate(R.layout.facebook_item, null);
vi.setClickable(true);
vi.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
String s = "test";
Toast.makeText(myContext, s, Toast.LENGTH_SHORT).show();
}
});
}
TextView text=(TextView)vi.findViewById(R.id.text);
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText(msg[position]);
text.getLineCount();
imageLoader.DisplayImage(data[position], image);
return vi;
}
What's important here is what's going on in the onClick
method. I would like to have an item parameter, but this is not possible for this OnClickListener. It's possible for normal listviews, I know that.
So - how can I determine which item is clicked?
PS: I've tried to think of using some sort of vi.setTag(<<number>>);
, but I don't see how this can be done without having the same tag set for all items of the listview.
As you move towards creating a Custom adapter, you want to reference your items using getItem(int position) as much as possible. Avoid referencing it using the actual arrays you pass in your Adapter constructor.
Try overriding the
getItem(int position)
andgetItemId(int position)
on your adapter, and use that instead of the arrays themselves inside yourgetView
.Why not use onItemClickListener on ListView itself?
Your Adapter should contain a List of one Object type (there is no strict rule, but it helps managing the item much easier). For example
Then your CustomAdapter will only contain
Then your getView will looks similar to this
Now your view will handle this as one object instead of one layout with multiple values.
Then we move all the click action to the Activity which ListView resides in.
This is the way I have my ListView with Lazy load ImageView as well. Then you will be able to access the object tied to that view and also the position which is clicked.
If you are so wish to separate msg and data. You can use setTag(id, obj); for both object, etc.
UPDATE: Example of my CustomAdapter
Inside Activity I handle item click action with
Hope this answer your question :)