How to start Fragment from Activity?

Rudra picture Rudra · May 23, 2015 · Viewed 38.6k times · Source

I have one Fragment:

ProductsFragments extends Fragment

and one Activity

AdminMenuActivity extends ActionBarActivity

I want to call ProductsFragments from AdminMenuActivity. I have used 2 options:

1)

FragmentManager fm = getSupportFragmentManager();
                for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
                    fm.popBackStack();
                }
                FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
                tx.replace(R.id.frame_layout, android.support.v4.app.Fragment.instantiate(AdminMenuActivity.this, fragments[1]));
                tx.commit();

2)

Intent intent1 = new Intent(AdminMenuActivity.this, ProductsActivity.class);
                startActivity(intent1);

Both are failed. I don't want to extend ProductsFragments with FragmentActivity because it doesn't give me supportedActionBar v7

So how do I call Fragment?

Answer

Dibyendu Mitra Roy picture Dibyendu Mitra Roy · Jun 30, 2016

Here is how you call a fragment from inside an Activity

Fragment fr = new FirstFragment();
fr.setArguments(args);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();

Assuming you have fragment_place represents the following:

<fragment android:name="com.company.appName.fragments.FirstFragment"
        android:id="@+id/fragment_place"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />