Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start Activity in adapter?

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.

like image 546
justicepenny Avatar asked Nov 16 '10 17:11

justicepenny


People also ask

How to call startactivity() from adapter context?

Thanks. 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 (). public class MyAdapter extends Adapter { private Context context; public MyAdapter (Context context) { this.context = context; } public View getView (...)

How to redirect to URL instead of activity from adapter class?

YourAdapter adapter = new YourAdapter (getContext (), (args) -> { startActivity (...); }); This link can be useful for you. If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.

Is it possible to add a callback from an adapter?

An old thread but adding for newer search results: this callback from adapter goes anti design pattern as Intents should be created and executed within activities listeners are best for this used case. For newer versions of sdk you have to set flag activity task.


1 Answers

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(...);              }          });      } } 
like image 195
Robby Pond Avatar answered Oct 02 '22 12:10

Robby Pond