Why is it necessary to implement OnFragmentInteractionListener when setting up a fragment?

Why is it necessary to implement OnFragmentInteractionListener when setting up a fragment?



I followed the official documentation: https://developer.android.com/guide/components/fragments#Creating. It provides the steps to set up a fragment.



First, create the fragment class (`extends Fragment')



Then create its layout (and, in fragment class' OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState), return one of the View' of this layout usinginflate`)


OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)


View' of this layout using



Choose an activity that will use this fragment. This activity must extends FragmentActivity and in order to use the fragment, it will contain calls to FragmentManager's methods, FragmentTransaction'smethods, etc.


extends FragmentActivity


FragmentManager


FragmentTransaction



However, doing this results in a "fatal exception":



java.lang.lang.lang.RuntimeException: com.example...TheActivity@efebfcf must implement OnFragmentInteractionListener



Questions



Why doesn't the documentation mention this problem?



In TheActivity (which uses the fragment TheFragment), I implemented TheFragment.OnFragmentInteractionListener (yes, TheFragment.OnFr...!). It's weird, isn't it? In addition, this listener provides this method: onFragmentInteraction(Uri uri) but what is it supposed to contain?


TheActivity


TheFragment


TheFragment.OnFragmentInteractionListener


TheFragment.OnFr...


onFragmentInteraction(Uri uri)




1 Answer
1



I'm pretty sure in the Fragment's onAttach method, it will say that the parent activity must implement the OnFragmentInteractionListener. This is to facilitate Fragment to Activity communication.


onAttach


OnFragmentInteractionListener



This is not required and the check in onAttach can be removed. In fact if you are not doing anything in the onAttach method then the whole method can be removed from the Fragment


onAttach


onAttach


Fragment



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)