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
?
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.
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().
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.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With