Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how check if an activity implements an interface after onAttach(Activity activity) has been depreacted

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");

    }
like image 378
Jose M Lechon Avatar asked Oct 21 '15 09:10

Jose M Lechon


2 Answers

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");

    }
like image 115
fractalwrench Avatar answered Oct 13 '22 00:10

fractalwrench


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");
}
like image 41
Umer Farooq Avatar answered Oct 13 '22 01:10

Umer Farooq