Calling a Fragment method from a parent Activity
Asked Answered
T

14

138

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.

Tobey answered 5/6, 2012 at 18:47 Comment(0)
T
230

not get the question exactly as it is too simple :

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>(); 
Tautog answered 5/6, 2012 at 18:51 Comment(12)
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.Tobey
Sorry, I left out the reference. The code pattern I am following is FragmentTabsPager. Thanks.Tobey
The situation will be different when neither u are having the ID nor the TAG associated with the fragment .Remember
how can I get the fragment id?Icecap
By doing this i ended up in a null object reference!Sexivalent
look in your <fragment tag in the xml file. You must have an id in there. It would be "example_fragment" to match the example code given.Simian
@Simian , what if I don't have fragment tag?Capsular
i'm pretty sure you have to, @VaclovasRekašiusJr. ! search through your XML filesSimian
I didn't declared fragment in xml... so i dont have fragment id, What will i do ??Davilman
In Kotlin use such syntax to suppress "this cast can never success" warning val fragm : MyFragment = fragmentManager.findFragmentById(R.id.my_fragment) as MyFragmentStyliform
java.lang.NullPointerException: Attempt to invoke virtual method ... I got this error when tried with your solution.Hedgepeth
getFragmentManger is now deprecated , Use FragmentActivity.getSupportFragmentManager()Ardoin
S
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(); 
Spectre answered 20/8, 2014 at 23:51 Comment(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?Langmuir
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.Spectre
S
10

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();
Sangria answered 11/6, 2014 at 23:26 Comment(0)
M
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();
    
Mallis answered 30/9, 2021 at 20:34 Comment(2)
you didnt use directly a public instance. is it because it helps for memory allocation if you use statc method with private static variable?Jeseniajesh
Hi da jowkar, I was tried many methods. Finally your method is working like a charm!!!. Thank you.Isometrics
L
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();

Lilian answered 14/12, 2015 at 7:22 Comment(0)
C
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");
Cycad answered 8/9, 2018 at 6:26 Comment(0)
C
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();
            }
        });
    }
}
Childhood answered 16/9, 2018 at 13:13 Comment(0)
P
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>(); 
}
Prohibit answered 6/3, 2017 at 0:32 Comment(0)
C
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

Childhood answered 16/9, 2018 at 11:10 Comment(0)
W
1
FragmentManager fm = getFragmentManager(); 
MainFragment frag = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
frag.<specific_function_name>(); 
Windermere answered 20/9, 2018 at 11:7 Comment(0)
K
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.

Kamala answered 5/3, 2019 at 14:7 Comment(0)
C
0
((HomesFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_container)).filterValidation();
Cardholder answered 11/6, 2020 at 7:51 Comment(1)
Please, feel free to explain why this solves the problem in a better way than the previously accepted answer.Trina
M
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();
}
Malarkey answered 18/9, 2020 at 22:3 Comment(0)
W
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();
Wilbert answered 21/9, 2022 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.