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.
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 (...)
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.
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.
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(...); } }); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With