136

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.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
gcl1
  • 4,070
  • 11
  • 38
  • 55

14 Answers14

227

not get the question exactly as it is too simple :

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>(); 
Zoe
  • 27,060
  • 21
  • 118
  • 148
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
  • 13
    OK that was easy, thanks (I'm brand new to fragments). Now the hard part is I can't seem to get a reference to the fragment in the first place. It's not defined in an XML layout, so I can't use findFragmentById(). And it's not clear to me from the code I'm following (ref above) how/where the fragment is even created. If it were I could just add a tag and use findFragmentByTag(). The AccountListActivity part of the example does have a call to beginTransaction().add(), but per my trace it's never called. This is where I am scratching my head. I appreciate any suggestions. – gcl1 Jun 05 '12 at 19:28
  • Sorry, I left out the reference. The code pattern I am following is [FragmentTabsPager](http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabsPager.html). Thanks. – gcl1 Jun 05 '12 at 19:48
  • The situation will be different when neither u are having the ID nor the TAG associated with the fragment . – Ankur Gautam Jan 20 '14 at 06:35
  • 43
    how can I get the fragment id? – Narendra Singh Oct 06 '15 at 11:16
  • 11
    By doing this i ended up in a null object reference! – Alok Rajasukumaran Jul 05 '16 at 05:02
  • look in your ** – Fattie Nov 28 '16 at 03:15
  • 5
    @Fattie , what if I don't have fragment tag? – Vaclovas Rekašius Jr. Aug 25 '17 at 00:38
  • i'm pretty sure you have to, @VaclovasRekašiusJr. ! **search through your XML files** – Fattie Aug 25 '17 at 03:52
  • 6
    I didn't declared fragment in xml... so i dont have fragment id, What will i do ?? – akash bs Feb 03 '18 at 09:09
  • In Kotlin use such syntax to suppress "this cast can never success" warning `val fragm : MyFragment = fragmentManager.findFragmentById(R.id.my_fragment) as MyFragment` – Jackky777 Apr 06 '18 at 13:54
  • java.lang.NullPointerException: Attempt to invoke virtual method ... I got this error when tried with your solution. – CleanCoder Jun 22 '20 at 06:19
  • getFragmentManger is now deprecated , Use FragmentActivity.getSupportFragmentManager() – ismail alaoui Nov 23 '20 at 16:27
82

If you are using “import android.app.Fragment;” Then use either:

1)

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

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

2)

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentByTag(“FragTagName”); 
fragment.specific_function_name(); 

Where FragTagName is the name u specified when u did:

TabHost mTabHost.newTabSpec(“FragTagName”)

If you are using “import android.support.v4.app.Fragment;” Then use either:

1)

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(); 
Gene
  • 10,819
  • 1
  • 66
  • 58
  • 2
    I have a CoordinatorLayout with id R.id.example_fragment, its returning null. I'm using import android.support.v4.app.Fragment; what to do? – Kishore Mar 14 '16 at 13:07
  • I suggest you post this as a new question and include your sample code. It's hard to tell the source of the problem without seeing the actual code. – Gene Mar 15 '16 at 15:38
9

If you're using a support library, you'll want to do something like this:

FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.my_fragment);
fragment.myMethod();
JDJ
  • 4,298
  • 3
  • 25
  • 44
7

Too late for the question but this is a easy way to get fragment instance and call methods in a fragment; you have to get instance of your fragment then call your public method:

In your fragment :

 private static yourFragment instance;

then in onCreateView of your fragment :

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
   Bundle savedInstanceState) {

        instance= this;

        View v = inflater.inflate(R.layout.fragment_tools, container, false);
        binding = FragmentToolsBinding.inflate(inflater, container, false);

        return v;
    }

and also in your fragment you have to have a static method that returns the instance:

public static yourFragment GetInstance()
{
    return instance;
}

then you have a public method in in your fragment that you want to call it like this:

public  void  theMethod()
{
    Toast.makeText(getActivity(), "Test", Toast.LENGTH_SHORT).show();
}

then you can get fragment instance and call your non static public method like this:

   yourFragment frag = yourFragment.GetInstance();
   frag.theMethod();
    
da jowkar
  • 181
  • 1
  • 8
  • you didnt use directly a public instance. is it because it helps for memory allocation if you use statc method with private static variable? – Emil Apr 03 '22 at 19:35
  • Hi da jowkar, I was tried many methods. Finally your method is working like a charm!!!. Thank you. – Jagadeesh Aug 24 '22 at 16:17
  • This works like a charm. Thank you soo much – M DEV Jul 02 '23 at 14:29
6
  1. If you're not using a support library Fragment, then do the following:

((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();

Chintan Shah
  • 1,744
  • 2
  • 26
  • 28
5

From fragment to activty:

((YourActivityClassName)getActivity()).yourPublicMethod();

From activity to fragment:

FragmentManager fm = getSupportFragmentManager();

//if you added fragment via layout xml
YourFragmentClass fragment = 
(YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();

If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:

YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
Bharat Vasoya
  • 351
  • 4
  • 7
4

you also call fragment method using interface like

first you create interface

public interface InterfaceName {
    void methodName();
}

after creating interface you implement interface in your fragment

MyFragment extends Fragment implements InterfaceName {
    @overide
    void methodName() {

    }
}

and you create the reference of interface in your activity

class Activityname extends AppCompatActivity {
    Button click;
    MyFragment fragment;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        click = findViewById(R.id.button);

        fragment = new MyFragment();

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               fragment.methodName();
            }
        });
    }
}
mXaln
  • 105
  • 11
3

I think the best is to check if fragment is added before calling method in fragment. Do something like this to avoid null exception.

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
  fragment.<specific_function_name>(); 
}
Surjit Singh
  • 269
  • 3
  • 8
1

First you create method in your fragment like

public void name()
{


}

in your activity you add this

add onCreate() method

myfragment fragment=new myfragment()

finally call the method where you want to call add this

fragment.method_name();

try this code

Quick learner
  • 10,632
  • 4
  • 45
  • 55
1
FragmentManager fm = getFragmentManager(); 
MainFragment frag = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
frag.<specific_function_name>(); 
Kishore Reddy
  • 2,394
  • 1
  • 19
  • 15
1

I don't know about Java, but in C# (Xamarin.Android) there is no need to look up the fragment everytime you need to call the method, see below:

public class BrandActivity : Activity
{
    MyFragment myFragment;

    protected override void OnCreate(Bundle bundle)
    {       
        // ...
        myFragment = new MyFragment();      
        // ...
    }

    void someMethod()
    {
        myFragment.MyPublicMethod();
    }
}

public class MyFragment : Android.Support.V4.App.Fragment
{
    public override void OnCreate(Bundle bundle)
    {
        // ...
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
    {
        // ...
    }

    public void MyPublicMethod()
    {
        // ...
    }   
}

I think in Java you can do the same.

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
0
((HomesFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_container)).filterValidation();
eagerprince
  • 115
  • 1
  • 5
  • 1
    Please, feel free to explain why this solves the problem in a better way than the previously accepted answer. – Xyz Oct 13 '20 at 13:36
0

Too late for the question but will post my answer anyway for anyone still needs it. I found an easier way to implement this, without using fragment id or fragment tag, since that's what I was seeking for.

First, I declared my Fragment in my ParentActivity class:

MyFragment myFragment;

Initialized my viewPager as usual, with the fragment I already added in the class above. Then, created a public method called scrollToTop in myFragment that does what I want to do from ParentActivity, let's say scroll my recyclerview to the top.

public void scrollToTop(){
    mMainRecyclerView.smoothScrollToPosition(0);
}

Now, in ParentActivity I called the method as below:

try{
   myFragment.scrollToTop();
}catch (Exception e){
   e.printStackTrace();
}
0

This works in my case hope anyone get help from this

OnDemandFrag frag = new OnDemandFrag();

using this to replace fragment in main

FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, frag).commit();

i just created a global instance of fragment in the MainActivity and then from this instance run function of Fragment

frag.hidelayer();
Zahid Iqbal
  • 394
  • 6
  • 12