I see in the Android Fragments Dev Guide that an "activity can call methods in a fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById()
or findFragmentByTag()
."
The example that follows shows how to get a fragment reference, but not how to call specific methods in the fragment.
Can anyone give an example of how to do this? I would like to call a specific method in a Fragment from the parent Activity. Thanks.
First you create method in your
fragment
likein your
activity
you add thisadd
onCreate()
methodfinally call the method where you want to call add this
try this code
not get the question exactly as it is too simple :
Update: For those who are using Kotlin
If you are using “import android.app.Fragment;” Then use either:
1)
Where R.id.example_fragment is most likely the FrameLayout id inside your xml layout. OR
2)
Where FragTagName is the name u specified when u did:
If you are using “import android.support.v4.app.Fragment;” Then use either:
1)
OR
2)
((FragmentName) getFragmentManager().findFragmentById(R.id.fragment_id)).methodName();
2. If you're using a support library Fragment, then do the following:
((FragmentName) getSupportFragmentManager().findFragmentById(R.id.fragment_id)).methodName();
From fragment to activty:
From activity to fragment:
FragmentManager fm = getSupportFragmentManager();
If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead: