Calling method of a dynamic fragment from Activity
I am stuck in this problem .
I want to call the method of an Abc fragment from my parent FragmentActivity which transacts fragments from a FrameLayout dynamically . Now the Activity has a broadcast receiver which listens to updates from a service . The activity can receive the Broadcast at any point even if Abc fragment is not currently the one displayed. now if i find a fragment using fragmentManager().findFragmentById(id) where id==id of the framelayout , i cannot simply cast it to Abc fragment because that gives error if it is not the one currently displayed . now how can i know that Abc is currently displayed so that i can pass it the update . I cannot implement the receive of update inside Abc itself because the Activity need the update for other purposes .
You can set a tag to the fragment when you create it
Fragment fragment = new MyFragment(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.fragment_host, fragment,"FragmentTag"); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(""); ft.commit();
and search it in this way
Fragment frag = (Fragment) getFragmentManager().findFragmentByTag("FragmentTag");