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

前端 未结 7 1037
再見小時候
再見小時候 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条回答
  •  情深已故
    2020-12-14 08:36

    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

    • Creating and Using Fragments
    • Android Fragment onAttach() deprecated

提交回复
热议问题