0

I have 2 Tabs and 2 Corresponding Fragments. On calling the LAUNCH Activity both Tabs were added and then the first one added will be shown. Thus the first Fragments onCreateView is called the second Fragments ones not.
In my case this is an issue because the first Fragment has to call methods on the second Fragment. Inside the second Fragment there is an Objectreference which will be set by calling the onCreateView in the second Fragment. Therefore I used following code snippet to solve this

actionBar.setSelectedNavigationItem(1);
actionBar.setSelectedNavigationItem(0);

It works but in my opinion there must be another possibility to solve this issue. Like calling the onCreateView of the second Fragment?

Here is the relevant code snippet. The listener is implemented as in android-dev Sample only with small changes not affecting my issue.

simplexFragment corresponds to the first Fragment
graphicFragment corresponds to the second Fragment

// adds two tabs
actionBar.addTab(actionBar.newTab().setText("Input").setTabListener(new TabListener(null,  "input_fragment")));

graphicFragment = new GraphicFragment();

actionBar.addTab(actionBar.newTab().setText("Graphic").setTabListener(new TabListener(graphicFragment, "graphic_fragment")));
simplexFragment.setGraphics(graphicFragment); // sets the internal reference!

actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// selects the Tab so the GraphicFragments onCreateView will be called
actionBar.setSelectedNavigationItem(1);
actionBar.setSelectedNavigationItem(0);

Thanks for support.

4

1 回答 1

0

就我而言,这是一个问题,因为第一个 Fragment 必须调用第二个 Fragment 上的方法。

这不是应该如何Fragments工作的。这个想法是一个Fragment应该是独立的和可重用的,一个人Fragment不应该知道另一个存在(或者至少不应该依赖任何其他的存在Fragment)。

例如,假设您有 3 个Fragments并且 ActivityA 使用 FragmentA 和 FragmentB,但您有另一个Activity(ActivityB) 使用 FragmentA 和 FragmentC。在这种情况下,FragmentA 不知道另一个Fragment是什么(B 或 C),甚至不应该期望有另一个Fragment

实现您想要的方法是在 上使用回调方法Activity并让它对任何其他Fragments(如果它们存在)执行操作。它可以通过在另一个上调用公共方法或在创建另一个时Fragments在“参数”中传递数据来做到这一点。BundleFragments

于 2013-04-22T17:43:15.070 回答