我如何调用片段的功能从另一个? [英] How do I call functions in fragment from another?

查看:128
本文介绍了我如何调用片段的功能从另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我把两个片段中的活动。我想要做的是隐藏的发言权碎片中的一个观点,当我点击的片段B.一个按钮,我在碎片中的隐藏功能,但我怎么称呼它在B片段? 我想:

<$p$p><$c$c>((FragmentA)getActivity().getFragmentManager().findFragmentById(R.id.fragment_a)).hideLive$p$pview();

但它给了我一个空指针异常......请帮助

解决方案

您不希望这样做一般。片段A和片段B不能直接通信,因为片段A和片段B可能不能同时在屏幕上在同一时间的所有时间的。他们可能是并排侧的大屏幕上,但通过在小屏幕上单独的活动显示。恕我直言,活动应调解片段之间的所有通信。如果你有两个片段过于紧耦合的,他们不应该是独立的片段摆在首位。

之所以这么说,您已经看到了 NullPointerException异常,因为存在与活动的ID。

没有片段

I put two fragments in an activity. What I want to do is to hide a view from say fragment A when I click a button in fragment B. I have the hiding function in fragment A but how do I call it in fragment B? I tried:

((FragmentA)getActivity().getFragmentManager().findFragmentById(R.id.fragment_a)).hideLivePreview();

but it gives me a null pointer exception...please help

解决方案

You do not want to do this in general. Fragment A and Fragment B should not directly communicate, since Fragment A and Fragment B may not both be on the screen at the same time all of the time. They might be side-by-side on a large screen but displayed via separate activities on smaller screens. IMHO, activities should mediate all communications between fragments. If you have two fragments that are too tightly coupled for that, they should not be separate fragments in the first place.

All that being said, you are getting a NullPointerException because there is no fragment with that ID in the activity.

这篇关于我如何调用片段的功能从另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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