How to start Fragment from an Activity
You can either add or replace fragment in your activity. Create a FrameLayout
in activity layout xml
file.
Then do this in your activity to add fragment:
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();
And to replace fragment do this:
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();
See Android documentation on adding a fragment to an activity or following related questions on SO:
Difference between add(), replace(), and addToBackStack()
Basic difference between add() and replace() method of Fragment
Difference between add() & replace() with Fragment's lifecycle
Simple way
Create a new java class
public class ActivityName extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null){ getSupportFragmentManager().beginTransaction() .add(android.R.id.content, new Fragment_name_which_you_wantto_open()).commit();} } }
in your activity where u want to call fragment
Intent i = new Intent(Currentactivityname.this,ActivityName.class); startActivity(i);
Another Method
Place frame layout in your activity where u want to open fragment
<FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="wrap_content"> </FrameLayout>
Paste this code where u want to open fragment
Fragment mFragment = null; mFragment = new Name_of_fragment_which_you_want_to_open(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.frameLayout, mFragment).commit();