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.
Solution 1:
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(...);
}
});
}
}
Solution 2:
When implementing the onClickListener
, you can use v.getContext.startActivity
.
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.getContext().startActivity(PUT_YOUR_INTENT_HERE);
}
});
Solution 3:
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() {
Intent intent= new Intent(context, ToActivity.class);
intent.putExtra("your_extra","your_class_value");
context.startActivity(intent);
}
});
}
}