How to implement OnFragmentInteractionListener

后端 未结 12 2635
花落未央
花落未央 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:26

    Answers posted here did not help, but the following link did:

    http://developer.android.com/training/basics/fragments/communicating.html

    Define an Interface

    public class HeadlinesFragment extends ListFragment {
        OnHeadlineSelectedListener mCallback;
    
        // Container Activity must implement this interface
        public interface OnHeadlineSelectedListener {
            public void onArticleSelected(int position);
        }
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
    
            // This makes sure that the container activity has implemented
            // the callback interface. If not, it throws an exception
            try {
                mCallback = (OnHeadlineSelectedListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                        + " must implement OnHeadlineSelectedListener");
            }
        }
    
        ...
    }
    

    For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Send the event to the host activity
        mCallback.onArticleSelected(position);
    }
    

    Implement the Interface

    For example, the following activity implements the interface from the above example.

    public static class MainActivity extends Activity
            implements HeadlinesFragment.OnHeadlineSelectedListener{
        ...
    
        public void onArticleSelected(int position) {
            // The user selected the headline of an article from the HeadlinesFragment
            // Do something here to display that article
        }
    }
    

    Update for API 23: 8/31/2015

    Overrided method onAttach(Activity activity) is now deprecated in android.app.Fragment, code should be upgraded to onAttach(Context context)

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
    
    
    @Override
    public void onStart() {
        super.onStart();
        try {
            mListener = (OnFragmentInteractionListener) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
    

提交回复
热议问题