javaandroidandroid-fragmentsandroid-framelayout

Get the fragment name or id


I have a framelayout called one time in my Activity and various time in other Fragment (passing by the same framelayout of the Activity).

In my MainActivity.class, I need to know in what fragment is my framelayout. For example, I need to know if framelayout is using MyFragment1.class or MyFragment2.class.

I need something like this (in this example, the log have to say me "you are in MyFragment1"):

FrameLayout frameLayout = (FrameLayout) findViewById(R.id.framelayout);

 getSupportFragmentManager().beginTransaction()
        .replace(R.id.framelayout,new MyFragment1())
        .commit();

if (framelayout.getname.equals("package.MyFragment1.class"))
 Log.d("debug", "you are in MyFragment1");
else if (framelayout.getname.equals("package.MyFragment2.class"))
 Log.d("debug", "you are in MyFragment2");

How can I do that?


Solution

  • I found the solution

    getSupportFragmentManager().beginTransaction()
         .replace(R.id.framelayout,new MyFragment1())
         .commit();
    
    final Fragment fragmentInFrame = getSupportFragmentManager().findFragmentById(R.id.framelayout);
    
    if (fragmentInFrame instanceof MyFragment1){
          Log.d("debug", "you are in MyFragment1");
    } else if (fragmentInFrame instanceof MyFragment2) {
          Log.d("debug", "you are in MyFragment2");
    }