I tried the following code:
Intent in= new Intent(Activity1.this,Fragment.class);
startactivity(in);
This is not how fragments work, fragments must be attached to an Activity
. To get your desired effect you must either start a new Activity
that contains the fragment you wish to show, or display the new fragment in the current Activity
.
In order to decide between which approach to take, I would consider how you want the Fragment
to affect the navigation of your interface. If you want the user to be able to get back to the previous view by using the Back button, you should start a new Activity
. Otherwise you should replace a view in your current Activity
with the new Fragment
.
Though, it is possible to add a Fragment
to the back stack, I would only attempt to do so if you are confident with the structure of your user interface.
To show a new fragment in the current Activity
you can use a FragmentTransaction
:
Fragment fragment = CustomFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_layout, fragment).commit();
write this code in your onCreate or in your intent:
FragmentManager fm = getSupportFragmentManager();
YourFragment fragment = new YourFragment();
fm.beginTransaction().add(R.id.main_contenier,fragment).commit();
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