Calling a fragment method from parent activity

I see in the Android Fragments Dev Guide that "an action can call methods in a fragment by getting a link to the fragment from FragmentManager using findFragmentById() or findFragmentByTag() ."

The following example shows how to get a link to a fragment, but not how to call certain methods in a fragment.

Can someone give an example of how to do this? I would like to call a specific method in a fragment from parent activity. Thank.

+85
android android-fragments
Jun 05 2018-12-18T00:
source share
5 answers

don't ask the question exactly the same as it is too simple:

 ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); fragment.<specific_function_name>(); 
+155
Jun 05 '12 at 18:51
source share

If you use "import android.app.Fragment;" Then use either:

one)

 ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); fragment.specific_function_name(); 

Where R.id.example_fragment is most likely the FrameLayout identifier inside your xml layout. OR

2)

 ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentByTag("FragTagName"); fragment.specific_function_name(); 

Where FragTagName is the name u specified with u:

 TabHost mTabHost.newTabSpec("FragTagName") 



If you use "import android.support.v4.app.Fragment;" Then use either:

one)

 ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.example_fragment); fragment.specific_function_name(); 

OR

2)

 ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag("FragTagName"); fragment.specific_function_name(); 
+65
Aug 20 '14 at 23:51
source share

If you are using a support library, you need to do something like this:

 FragmentManager manager = getSupportFragmentManager(); Fragment fragment = manager.findFragmentById(R.id.my_fragment); fragment.myMethod(); 
+8
Jun 11 '14 at 23:26
source share
  • If you are not using the Snippet support library, follow these steps:

((FragmentName) getFragmentManager().findFragmentById(R.id.fragment_id)).methodName();


2. If you are using the Snippet support library, follow these steps:

((FragmentName) getSupportFragmentManager().findFragmentById(R.id.fragment_id)).methodName();

+3
Dec 14 '15 at 7:22
source share

I think it is best to check if a fragment has been added before calling the method in the fragment. Do something similar to avoid a null exception.

 ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); if(fragment.isAdded()){ fragment.<specific_function_name>(); } 
+3
Mar 06 '17 at 0:32
source share



All Articles