Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for an Activity to know what fragment was just created?

Tags:

android

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 Fragments attaching itself to it so that it may respond to it.

like image 481
Mark Lapasa Avatar asked Feb 18 '12 02:02

Mark Lapasa


People also ask

How do I find a fragment in an activity?

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.

How do you know if a fragment is recreated?

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.

Can fragment be created without activity?

Fragment can't be initiated without Activity or FragmentActivity.


1 Answers

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)

like image 153
Ankur Kumar Avatar answered Oct 06 '22 23:10

Ankur Kumar