How to start Activity in adapter?

justicepenny picture justicepenny · Nov 16, 2010 · Viewed 107.8k times · Source

I have a ListActivity with my customized adapter and inside each of the view, it may have some buttons, in which I need to implement OnClickListener. I need to implement the OnClickListener in the adapter. However, I don't know how to call the function like startActivity() or setResult(). Since the adapter doesn't extend to Activity.

So what is the best way to solve this problem?

Thanks.

Answer

Robby Pond picture Robby Pond · Nov 16, 2010

Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().

pseudo-code

public class MyAdapter extends Adapter {
     private Context context;

     public MyAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}