3

I need to check the current displayed fragment to avoid relaunch of same fragment class

To launch the fragment used code :

private Class mFragmentClass;

mFragmentClass = InfoFragment.class;

if (null != mFragmentClass) {
  try {
     mFragment = (Fragment) mFragmentClass.newInstance();
     FragmentManager fragmentManager = getSupportFragmentManager();
     fragmentManager.beginTransaction().replace(R.id.content_navigation_menu, mFragment).commit();
  } catch (InstantiationException exception) {
     exception.printStackTrace();
  } catch (IllegalAccessException exception) {
     exception.printStackTrace();
  }
}

Need to check current displayed fragment:

if(mFragment instanceof (Fragment)mFragmentClass.newInstance())

is giving compile time error

[),Expected,Type Expected]

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Jeelan
  • 173
  • 1
  • 11
  • 1
    The java instanceof operator is used to test whether the object is an instance of the specified type.It expects a class. Possible duplicate : https://stackoverflow.com/questions/9294603/get-currently-displayed-fragment – Swati Aug 09 '17 at 07:47

2 Answers2

2

You can make a static String in your Activity where you are opening the fragments

public static String currentFragment = "";

then in every fragments onResume you can give the name of the fragment to that string like this

MainActivity.currentFragment = "currentFrag";

Then you can check it whenever you want.

Anmol317
  • 1,356
  • 1
  • 14
  • 31
2

Try this for checking types that are only known at runtime:

mFragmentClass.isInstance(mFragment)
orip
  • 73,323
  • 21
  • 116
  • 148