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
callback from adapter to activity can be done using registering listener in form of interface: Make an interface:
public MyInterface{
public void yourmethod(//incase needs parameters );
}
In Adapter Let's Say MyAdapter:
public MyAdapter extends BaseAdapter{
private MyInterface listener;
MyAdapter(Context context){
try {
this. listener = (( MyInterface ) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement MyInterface");
}
//do this where u need to fire listener l
try {
listener . yourmethod ();
} catch (ClassCastException exception) {
// do something
}
In Activity Implement your method:
MyActivity extends AppCompatActivity implements MyInterface{
yourmethod(){
//do whatever you want
}
}
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);
}
});
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(...);
}
});
}
}
For newer versions of sdk you have to set flag activity task.
public void onClick(View v)
{
Intent myactivity = new Intent(context.getApplicationContext(), OtherActivity.class);
myactivity.addFlags(FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(myactivity);
}
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);
}
});
}
}
If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.
btnInstall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(link));
intent.setData(Uri.parse(link));
context.startActivity(intent);
}
});