44

I set the content view in the FragmentActivity, and the activity will create the fragment instance for me according to the class name specified in the layout file. But how can I get that fragment instance?

public class MyActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle extra) {
        super.onCreate(extra);
        setContentView(R.layout.page_fragment);
    }
}

layout/page_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/pageview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:name="org.xi.android.PageFragment" />
LarsH
  • 27,481
  • 8
  • 94
  • 152
David S.
  • 10,578
  • 12
  • 62
  • 104

2 Answers2

102

You can use use findFragmentById in FragmentManager.

Since you are using the Support library (you are extending FragmentActivity) you can use:

getSupportFragmentManager().findFragmentById(R.id.pageview)

If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):

getFragmentManager().findFragmentById(R.id.pageview)

Please consider that using the support library is recommended even on Honeycomb+.

kingston
  • 11,053
  • 14
  • 62
  • 116
  • Please see my related question: http://stackoverflow.com/questions/24833912/refresh-fragment-ui-from-fragmentactivity – Dr.jacky Jul 19 '14 at 07:42
  • this won't work if you have multiple instances of the frame fragment on the backstack. – dy_ Sep 21 '14 at 22:00
40

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);
Liuting
  • 1,098
  • 17
  • 35
Meriam
  • 945
  • 8
  • 18
  • 3
    'tis the right answer. The other (validated) answer doesn't work in the case of fragments using support library v4, as used in the question (FragmentActivity only present in support library) – Thibault D. Feb 18 '13 at 12:22