views:

59

answers:

2

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.setOnClickListener(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.

+1  A: 

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.

WarrenFaith
+3  A: 

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);
    }
}
Sephy
+1 works, too. But I chosse Warrens answer because using the override saves me a line of code because I don't need to do `findViewById(...)` to get my ListView.And his answer was a whole second earlier :D
SchlaWiener
That's fine for me, but you will see that if you want to do other things to your ListView, you will have to call it anyway. Good luck
Sephy