An Activity
may inflate an arbitrary layout xml that may or may not have a Fragment
placeholder in it.
If it does , the Fragment
will be instantiated and attached to the Activity
.
Is there any way to get a reference to the Fragment
from the Activity
that has been attached to it ?
FragmentManger.findFragmentById()
assumes you know the ID in advance to make it work but in this situation I am proposing, it is not available.
The behavior I'd ideally like to have is that the Activity
is aware of any Fragment
s attaching itself to it so that it may respond to it.
To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.
The simple answer to that would be call getData from onCreate() , but then I get nullPointer, because at that point I have no AsyncTask . So I need to somehow to know whether fragment was just have been created or it was just detached and then attached again.
Fragment can't be initiated without Activity or FragmentActivity.
Whenever a fragment is attached to an activity the following callback method is called with the fragment attached as the parameter, you can use it store the reference.
onAttachFragment(Fragment fragment)
http://developer.android.com/reference/android/app/Activity.html#onAttachFragment(android.app.Fragment)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With