-3

Hello Everyone, On my main Activity, I have some menus. What I want to do is that, if a user click on the menu, he/she must navigate, or must be landed on a Fragment.

I know from Activity to Activity is just pass an Intent eg: Intent intent New Intent (Activity1.this. Activity2.class); And From Fragment to Activity eg: Intent intent New Intent (getContext() Activity2.class);

But how to Intent from an Activity to a Fragment? Or have to Navigate from An Activity to a Fragment? Is that possible ?

Does anyone have an idea how to do that ? thanks a lot.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

2 Answers2

0
Try this,
   Fragment fragment = new Fragment_class();
    FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment).addToBackStack(null);
        fragmentTransaction.commit(); 
sky00145
  • 24
  • 5
0

The intent is only used with Activities, Services, and BroadcastReceivers. A fragment as its name suggests is part of an Activity that adds the dynamic content replacement to it.

Your options:

  1. A parent activity with two fragments that get replaced dynamically
  2. Two Activities that each have a fragment inside.
  3. Using Android Navigation Component which handles most of the transactions.

When Working with fragments you have two options:

  1. Using Static Fragments
<fragment
    android:name="com.example.myapp.FragmentA"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />   
  1. Dynamic fragment replacement

Inside Activity's XML

<FrameLayout
    android:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Inside Activity's Java File:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frameLayout, SecondFragment());
transaction.commit();

You can also use this component as part of the android JetPack Android Navigation Component

Arrowsome
  • 2,649
  • 3
  • 10
  • 35