Android how do I get the position of a row in an ListView from an onClickHandler()
I have a view that has a custom ArrayAdapter as a ListAdapter. Customer is a Poco:
public class Customer {
public String LastName;
public boolean IsActive;
}
What works: I have sucesfully bound my ArrayList to my ListView, the LastName is displayed as a text and the CheckBox is checked or not (depending on IsActive) but now I want to update the ArrayList everytime the checkbox is checked but I can't access the position in the OnClickListener:
setListAdapter(new ArrayAdapter<Customer>(this, android.R.layout.simple_list_item_checked, items) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (null == convertView) {
row = mInflater.inflate(android.R.layout.simple_list_item_checked, null);
} else {
row = convertView;
}
CheckedTextView ctv = (CheckedTextView) row.findViewById(android.R.id.text1);
ctv.setText(getItem(position).LastName);
ctv.setChecked(getItem(position).IsChecked);
ctv.setOnClic开发者_JAVA百科kListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckedTextView ctv = (CheckedTextView) v;
ctv.toggle();
// this does not work because I don't have the position
getItem(position).IsChecked = (ctv).isChecked();
}
});
return row;
}
});
I thought about inheriting from CheckedTextBox and adding a custom property setPosition/getPosition
to store the position for later use or even add a reference to the related object but I suppose there is an existing solution I can't find atm.
You should use the ListView to give it an onItemClickListener and pass it an AdapterView which would look like that :
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
// here you have th view, the position, everything you need to have fun ;=)
//you can acces the content of your adapter here with :
mAdapter.getItem(pos);
}
}
I would handle the click not by the row, but by the ListActivity
public void onListItemClick(ListView l, View v, int position, long id)
that gives you everything you need. Override the method in your ListActivity.
精彩评论