Get Fragment instance in Activity

17,760

Try this

getSupportFragmentManager().beginTransaction()
                .add(R.id.container,new MyFragment(),"MyFragment").commit();

for get the fragment

MyFragment frag = ((MyFragment) getSupportFragmentManager().findFragmentByTag("MyFragment"));
Share:
17,760
Zar E Ahmer
Author by

Zar E Ahmer

Being an Android developer, making creative things gives me another level of Happiness regardless of how much money I make. I'm a creative and gregarious technologist with a keen interest in development of innovative applications. Currently Team Lead at Planet Beyond Current Product: https://play.google.com/store/apps/details?id=com.talkhome&hl=en

Updated on June 07, 2022

Comments

  • Zar E Ahmer
    Zar E Ahmer about 2 years

    I have added Fragment to Activity like

    getSupportFragmentManager().beginTransaction()
                        .add(R.id.container,new MyFragment).commit();
    

    where container is the id of FrameLayout

     <FrameLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    

    Now how could i get the instance of Fragment in Activity like this

    I have to call a method of Fragment A after getting result from Fragment B.

    I have created an interface in Fragment B and implemented it in Activity.Now i have to pass the result to Fragment A. I am unable to get the instance of Fragment A.

    One thing i don't wanna do is to create a private instance of Fragment A in Activity and call it's method.