8

Since onAttach(Activity) has been deprecated on SDK 23, which is the best method in the Fragment lifecycle for checking if an Activity is implementing an interface?

this code is no longer right and in the future this method could even be removed.

 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (activity instanceof OnInterfaceOfFragmentListener)
            mCallback = (OnInterfaceOfFragmentListener) activity;
        else
            throw new RuntimeException("OnInterfaceOfFragmentListener not implemented in activity");

    }
Jose M Lechon
  • 5,766
  • 6
  • 44
  • 60
  • first you shouldn't worry much about this for some time ... next there is new `onAttach(Context)` method ... but still ... the Context passed via this method will be the Activity ... – Selvin Oct 21 '15 at 09:46

2 Answers2

17

The code will remain the same, just you should be using a Context parameter rather than an Activity, as per the documentation.

@Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof OnInterfaceOfFragmentListener)
            mCallback = (OnInterfaceOfFragmentListener) context;
        else
            throw new RuntimeException("OnInterfaceOfFragmentListener not implemented in context");

    }
fractalwrench
  • 4,028
  • 7
  • 33
  • 49
3

You can use the alternative method provided by the framework. It has the same place in the lifecycle as onAttach(Activity)

onAttach(Context context)

And for checking if it implments a certain interface:

public void onAttach(Context context) {

  if(context instanceOf YourInterface) {
       // do stuff
  }
  else
     throw new RuntimeException("XYZ interface not implemnted");
}
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67