views:

43

answers:

1

Hi All,

I currently have a ListView in my Android app that has a CheckBox on the side.

When the checkbox is changed I want to get some info from the listview row that the button is in and then persist it, however, I can not work out how to get the row data from the onClickChanged listener.

My listview is populated using a custom JSONObject listadapter, I am hoping it is something similar to working out what row is selected when detecting the onLongTouch - for example below is the code I use to get the relevant JSON object for the row selected on a longTouch:

public boolean onContextItemSelected(MenuItem item) { 
        //get row selected information
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        JSONObject selected = (JSONObject) getListAdapter().getItem(menuInfo.position);

The above is obviously within my ListActivity, and my onCheckChanged listener would not be in the same activity (as it is defined in the row rather than the list)

Any help would be appreciated!

+1  A: 

One possible way to solve this is to attach some info to the checkbox when binding occurs.

In your Adapter, add (or modify) the bindView override like this to add a tag thatcontains the context information you need:

    @Override
    public void bindView( View view, Context context, Cursor cursor){
        CheckBox checker = (CheckBox)view.findViewById(R.id.checkbox);

        checker.setOnCheckedChangeListener(MyActivity.this);
        checker.setTag(Long.valueOf(cursor.getLong(cursor.getColumnIndex(BaseColumns._ID))));
        // call super class for default binding
        super.bindView(view,context,cursor);
    }

(or attach any other value to the checkbox that helps you identify the item, e.g. the propery name or index)

Then, in the onCheckedChanged, you can refer to this information to identify the item that was changed:

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Long id = (Long) buttonView.getTag();
    if ( id!=null)
        Log.d(TAG, "onCheckedChanged id="+id);

}
Thorstenvv
Thanks! I have actually just worked out exactly the same approach using a Tag on the checkbox last night! (I've gone through the problem and solution, a long with my actual code here http://automateddeveloper.blogspot.com/2010/09/everything-you-need-to-know-about.html)
rhinds