How to implement OnFragmentInteractionListener

后端 未结 12 2663
花落未央
花落未央 2020-11-22 06:25

I have a wizard generated app with navigation drawer in android studio 0.8.2

I have created a fragment and added it with newInstance() and I get this error:

12条回答
  •  深忆病人
    2020-11-22 07:12

    For those of you who still don't understand after reading @meda answer, here is my concise and complete explanation for this issue:

    Let's say you have 2 Fragments, Fragment_A and Fragment_B which are auto-generated from the app. On the bottom part of your generated fragments, you're going to find this code:

    public class Fragment_A extends Fragment {
    
        //rest of the code is omitted
    
        public interface OnFragmentInteractionListener {
            // TODO: Update argument type and name
            public void onFragmentInteraction(Uri uri);
        }
    }
    
    public class Fragment_B extends Fragment {
    
        //rest of the code is omitted
    
        public interface OnFragmentInteractionListener {
            // TODO: Update argument type and name
            public void onFragmentInteraction(Uri uri);
        }
    }
    

    To overcome the issue, you have to add onFragmentInteraction method into your activity, which in my case is named MainActivity2. After that, you need to implements all fragments in the MainActivity like this:

    public class MainActivity2 extends ActionBarActivity
            implements Fragment_A.OnFragmentInteractionListener, 
                       Fragment_B.OnFragmentInteractionListener, 
                       NavigationDrawerFragment.NavigationDrawerCallbacks {
        //rest code is omitted
    
        @Override
        public void onFragmentInteraction(Uri uri){
            //you can leave it empty
        }
    }
    

    P.S.: In short, this method could be used for communicating between fragments. For those of you who want to know more about this method, please refer to this link.

提交回复
热议问题