是否有可能从activitiy的onCreate访问片段的UI元素 [英] Is it possible to access fragment's UI elements from activitiy's onCreate
问题描述
作为标题说:是否有可能获得与该活动的onCreate()方法中初始化所有UI元素当前可见的片段?
我采取分离成模型,视图和控制器与处理业务逻辑和UI事件独立的控制器类。因此,他们需要将当前片段的引用。这些控制器在活动的onCreate()方法初始化因此我需要该方法中的初始化片段
As the headline says: Is it possible to get the currently visible fragment with all UI elements initialized within the onCreate() method of the activity? I am implementing a separation into model, view and controller with separate controller classes that handle business logic and UI events. Therefore they need a reference to the current fragment. These controllers are initialized in the onCreate() method of the activity hence I need the initialized fragment within that method.
我欢迎任何样的建议:)
I welcome any kind of advice :)
编辑:
添加了一些code为了更好的理解:
我用匕首依赖注入,想做到这一点在onCreate()方法。正如我以前说过我的控制器需要一个的MapView元素。这就是为什么我想有初始化的MapView元素的片段。
Adding some code for better understanding: I'm using dagger for dependency injection and would like to do this in the onCreate() method. As I said before my controller needs an the mapView element. And that is why I would like to have a fragment with the mapView element initialized.
MapActivity#的onCreate(捆绑):
MapActivity#onCreate(Bundle):
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_layout);
MyMapFragment fragment = new MyMapFragment();
getFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment, "fragment")
.commit();
ObjectGraph.create(new Module(fragment.getMapView())).inject(this);
}
activity_layout.xml
activity_layout.xml
<android.support.v4.widget.DrawerLayout>
<FrameLayout
android:id="@+id/activity_container"
... />
<ListView .../>
</android.support.v4.widget.DrawerLayout>
fragment_layout.xml
fragment_layout.xml
<RelativeLayout>
<org.osmdroid.map.MapView
android:id"@+id/mapview"
... />
<Button .../>
</RelativeLayout>
2ND编辑:
因此,它似乎是不可能的......耶为downvote ^^
2ND So it seems like that is not possible... Yay for the downvote ^^
推荐答案
默认情况下,没有。在的onCreate()
运行时间的活动,该片段没有连接到活动呢。
By default, no. At the time activity onCreate()
runs, the fragment is not attached to the activity yet.
访问片段的观点正确的地方是在片段本身。考虑将控制器分配在其生命周期内的片段,如 onCreateView()
或 onViewCreated()
。
Right place to access a fragment's views is in the fragment itself. Consider putting the controller assignments in the fragment within its lifecycle such as onCreateView()
or onViewCreated()
.
有可能显式运行使用排队片段交易<一个href=\"http://developer.android.com/reference/android/app/FragmentManager.html#executePendingTransactions%28%29\"相对=nofollow> executePendingTransactions()
,或隐式后 super.onStart()
已在活动的生命周期中运行。之后该片段视图在活动视图层次访问。
It is possible to explicitly run queued up fragment transactions using executePendingTransactions()
, or implicitly after super.onStart()
has been run in the activity lifecycle. After that the fragment views are accessible in the activity view hierarchy.
这篇关于是否有可能从activitiy的onCreate访问片段的UI元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!