onAttach(Activity) deprecated: where I can check if the activity implements callback interface

前端 未结 7 1020
再見小時候
再見小時候 2020-12-14 07:43

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         


        
7条回答
  •  -上瘾入骨i
    2020-12-14 08:29

    I never had to use onAttach(Context context) yet but I think your code is basically good. So here is my suggestion, using your code:

    public void onAttach (Context context) {
       super.onAttach(context);
       try {
            Activity activity = (Activity) context;
            mListener = (SellFragmentListener) activity;
       } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement SellFragmentListener");
        }
    }
    

    The main difference is that I can typecast context to get the Activity. This is because Context can propagate to the subclass which is the activity.

    Another issue, API 23 is still far away from now for us to worry. If you do worry, using build pragma (static Build) may be a good option.

提交回复
热议问题