I have a ListView with one button per row. If I needed to get the data when the row gets clicked, then it would be pretty easy to do the following inside the onItemClickListener:
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
CustomType type = (CustomType) arg0.getItemAtPosition(arg2); //get data related to position arg2 item
}
});
Actually, the thing is that I need to get the data(i.e: CustomType object) when the button of the ListView's row get's clicked, and not the row itself. Since OnClickListener doesn't have something like AdapterView<?>
as a
parameter(obviously), I would like to know how can I handle this?.
So far, It occurred to me getting the button's parent, which is the listview, and somehow getting in which row's position the clicked button is, and then
call something like:
myAdapter.getItem(position);
but is just an idea, so please, I'll appreciate some help over here.
You're probably using a custom adapter for your ListView
so the easiest way to do what you want is to set in the getView()
method of the adapter the position
parameter as the tag for the Button
. You could then retrieve the tag in the OnClickListener
and you'll know then which row was clicked:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//...
button.setTag(Integer.valueOf(position));
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Integer rowPosition = (Integer)v.getTag();
}
});
//...
}
You could also extract the data from the row views. This will work if all the data for the row can be found in the view from that row:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout row = (LinearLayout)v.getParent(); I assumed your row root is a LinearLayout
// now look for the row views in the row and extract the data from each one to
// build the entire row's data
}
});