Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start Fragment from Activity?

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?

like image 410
Rudra Avatar asked May 23 '15 12:05

Rudra


People also ask

How do you go from activity to fragment?

Can I go from fragment to activity Android? You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

How do you start a fragment from a fragment?

First you need an instance of the 2nd fragment. Then you should have objects of FragmentManager and FragmentTransaction. The complete code is as below, Fragment2 fragment2=new Fragment2(); FragmentManager fragmentManager=getActivity().

How do I call fragment from activity Kotlin?

This example demonstrates how to call an activity method from a fragment in an Android App using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

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" />
like image 165
Dibyendu Mitra Roy Avatar answered Oct 16 '22 01:10

Dibyendu Mitra Roy