3

This is a stylistic question more than an actual "how can this be done," but the basic situation is this: I have an Activity MyActivity which contains a MapFragment, as well as a List of Renderers which are my own class that takes care of displaying some data. The Renderers also have ViewPagers which get their content views from yet another class, let's call it ViewPagerTab. Sometimes, something happens in some of these ViewPagerTabs that necessitates the update of the map in the top level Activity. There are, as I see it, a few approaches:

1) Both my Renderers and my ViewPagerTabs contain a reference to the context. If I cast the context as MyActivity I can access its map parameter.

2) By using the reference to the context, I can call getSupportFragmentManager().findFragmentById(R.id.map)).getMap() on it and get the map that way.

3) I can pass the map down from the Activity to the Renderers to the ViewPagerTabs as they are created so the map is accessible in each as a class variable.

4) Use a BroadcastReceiver in my Activity and send a message to it when the map needs updating from my ViewPagerTab.

Have I missed anything? What's the best/cleanest way of doing this?

4

4 回答 4

4

这节课可能会给你一些思路: 与其他Fragment通信 基本上思路就是在Fragment等子单元中定义一个接口,然后在父Activity中实现。然后,在 Fragment 中实际调用接口中的方法。

于 2013-10-08T19:30:04.140 回答
1

另一种选择是创建一个类extends Application。在那里,您可以“共享和声明”许多非上下文特定变量(如美化容器,但您不必创建多个实例或进行查找)。

需要在您的清单中进行一些设置,然后您的所有活动都可以调用MyApp app = (MyApp) this.getApplication();(或在片段中,通过 onAttach 活动的.getApplication()

于 2013-10-08T19:27:04.400 回答
0

标准的方法是定义一个监听器接口,但我发现这很麻烦。Otto是一个非常好的选择,您至少应该在做出决定之前考虑一下。

于 2013-10-08T19:33:48.887 回答
0

我认为这有点过头了,但是包裹呢。我认为由于数据的动态性质,它不起作用,但它是活动之间进行通信的一种方式。

于 2013-10-08T19:50:05.033 回答