Search code examples
androidandroid-listviewsimplecursoradapterandroid-cursoradapter

Accessing activity's state in CursorAdapter subclass


I'm writing a fairly complex ListView, which (among other things) requires formatting Views in each list item.

To give me full control over how the views are bound in each list item, I subclassed CursorAdapter in this manner:

public class MyAdapter extends CursorAdapter {

    public final LayoutInflater mInflater;

    public MyAdapter(Context context, Cursor c) {
        super(context, c);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final ToggleButton tButton = (ToggleButton) view.findViewById(R.id.tbutton);
        tButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // start activity based on a pending intent
            }
        });     

    }
}

The issue is that my ToggleButton click listener should start an activity based on a pending intent. The pending intent is instantiated in the activity which utilises this customized adapter.

I'm aware I could have used a SimpleCursorAdapter in the main Activity with a ViewBinder so that launching the intent would only be necessary from the main Activity. But SimpleCursorAdapter is not quite right since I don't map columns straight to views.

However, the alternative I have here would suggest accessing the main Activity's data from a cursor subclass. I feel that there must be a better way to design the application.


Solution

  • Taking a cue from the API Demos - specifically EfficientAdapter, I have declared the CursorAdapter sublcass as an inner class of my activity.

    This avoids passing the pending intent around outside of the main activity.

    Source: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html