Calling a Fragment method from a parent Activity

AndroidAndroid Fragments

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

not get the question exactly as it is too simple :

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

Solution 2 - Android

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

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

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:

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

OR

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

Solution 3 - Android

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

Solution 4 - Android

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

Solution 5 - Android

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

Solution 6 - Android

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

Solution 7 - Android

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

Solution 8 - Android

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

Solution 9 - Android

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

Solution 10 - Android

FragmentManager fm = getFragmentManager(); 
MainFragment frag = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
frag.<specific_function_name>(); 

Solution 11 - Android

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.

Solution 12 - Android

((HomesFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_container)).filterValidation();

Solution 13 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiongcl1View Question on Stackoverflow
Solution 1 - AndroidDheeresh SinghView Answer on Stackoverflow
Solution 2 - AndroidGeneView Answer on Stackoverflow
Solution 3 - AndroidJDJView Answer on Stackoverflow
Solution 4 - AndroidChintan ShahView Answer on Stackoverflow
Solution 5 - Androidda jowkarView Answer on Stackoverflow
Solution 6 - AndroidBharat VasoyaView Answer on Stackoverflow
Solution 7 - AndroidSurjit SinghView Answer on Stackoverflow
Solution 8 - Androiduser10143207View Answer on Stackoverflow
Solution 9 - Androiduser10143207View Answer on Stackoverflow
Solution 10 - AndroidKishore ReddyView Answer on Stackoverflow
Solution 11 - AndroidMehdi DehghaniView Answer on Stackoverflow
Solution 12 - AndroideagerprinceView Answer on Stackoverflow
Solution 13 - AndroidHussein NasereddineView Answer on Stackoverflow