Before API 23 I used Fragment\'s onAttach methods to get my listener instance, then the reference is cleaned inside onDetach. ex:
@Override
public void onAtt
As shown in Zsolt Mester's answer, onAttach(Activity activity) is deprecated in favor of onAttach(Context context). Thus, all you need to do is check to make sure the context is an activity.
In Android Studio if you go to File > New > Fragment, you can get the auto generated code that will contain the proper syntax.
import android.support.v4.app.Fragment;
...
public class MyFragment extends Fragment {
private OnFragmentInteractionListener mListener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate fragment layout
return inflater.inflate(R.layout.fragment_myfragment, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Notes
Since the parent Activity must implement our OnFragmentInteractionListener (the arbitrarily named interface), checking (context instanceof OnFragmentInteractionListener) ensures that the context is actually the activity.
Note that we are using the support library. Otherwise onAttach(Context context) wouldn't be called by pre API 23 versions of Android.
See also