Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the fragment instance from the FragmentActivity?

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" /> 
like image 664
David S. Avatar asked Dec 16 '11 09:12

David S.


People also ask

How do you get FragmentActivity in a fragment?

use getActivity() method. Which will return the enclosing activity for the fragment.

How do I get the current fragment from supportFragmentManager?

FragmentManager fragMgr = getSupportFragmentManager(); FragmentTransaction fragTrans = fragMgr. beginTransaction(); MyFragment myFragment = new MyFragment(); //my custom fragment fragTrans. replace(android. R.

How do I call fragment from activity OnClickListener in Android?

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour... Creating a new Activity really defeats the whole purpose to use fragments anyway... very counter productive.


2 Answers

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+.

like image 105
kingston Avatar answered Oct 13 '22 20:10

kingston


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); 
like image 26
Meriam Avatar answered Oct 13 '22 19:10

Meriam