设置片段时,为什么必须实现OnFragmentInteractionListener? [英] Why is it necessary to implement OnFragmentInteractionListener when setting up a fragment?

查看:89
本文介绍了设置片段时,为什么必须实现OnFragmentInteractionListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了官方文档: https://developer.android.com/guide/components/fragments#Creating .它提供了设置片段的步骤.

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

  1. 首先,创建片段类(`extendeds Fragment')

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

然后创建其布局(并在片段类的 OnCreateView(LayoutInflater inflater,ViewGroup容器,捆绑的saveInstanceState)中,使用 inflate`)

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

选择一个将使用此片段的活动.此活动必须扩展FragmentActivity ,并且为了使用该片段,它将包含对 FragmentManager 的方法, FragmentTransaction 的方法等的调用.

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.

但是,这样做会导致致命异常":

java.lang.lang.lang.RuntimeException:com.example ... TheActivity @ efebfcf必须实现OnFragmentInteractionListener

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

问题

  1. 文档为什么没有提到这个问题?

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

TheActivity (使用片段 TheFragment )中,我实现了 TheFragment.OnFragmentInteractionListener (是的, TheFragment.OnFr ... !).很奇怪,不是吗?此外,此侦听器还提供以下方法: onFragmentInteraction(Uri uri),但是它应该包含什么?

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?

推荐答案

我很确定Fragment的 onAttach 方法中,它将说父活动必须实现 OnFragmentInteractionListener .这是为了促进片段到活动"的通信.

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 中的签入.实际上,如果您没有在 onAttach 方法中执行任何操作,则可以从 Fragment

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

这篇关于设置片段时,为什么必须实现OnFragmentInteractionListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆