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

守給你的承諾、 提交于 2021-01-29 13:55:05

问题


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

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

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

  3. 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.

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

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

Questions

  1. Why doesn't the documentation mention this problem?

  2. 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?


回答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.

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



来源:https://stackoverflow.com/questions/52343383/why-is-it-necessary-to-implement-onfragmentinteractionlistener-when-setting-up-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!