I have a method (fragmentUsing), I need to pass it one from instances of a class of type (fragment1 or fragment2 or fragment3 or fragment4):

Fragment1 fragment1=NewFragment1(); Fragment2 fragment2=NewFragment2(); Fragment3 fragment3=NewFragment3(); Fragment4 fragment4=NewFragment4(); public void fragmentUsing (** ***){ mFragmentManager = getFragmentManager(); android.app.FragmentTransaction fragmentTransaction = mFragmentManager .beginTransaction(); fragmentTransaction.replace(R.id.mainLayout,***,TAG_1); fragmentTransaction.commit(); } 

How to do it ?

  • An instance of a class is an object. Declare its type and name in the description of the method (get the parameter ). For example, public void fragmentUsing (int i) . call so: fragmentUsing(4) . 4 here will be an instance of the class int - Vladyslav Matviienko
  • @metalurgus is just a type of dynamic. - user208111
  • types are not dynamic - Vladyslav Matviienko

1 answer 1

Parameter type specify the one from which all these NewFragment are NewFragment . If they are inherited from Fragment , then specify it.

 public void fragmentUsing (Fragment fragment){ mFragmentManager = getFragmentManager(); android.app.FragmentTransaction fragmentTransaction = mFragmentManager .beginTransaction(); fragmentTransaction.replace(R.id.mainLayout, fragment,TAG_1); fragmentTransaction.commit(); } 
  • Thanks, talk with android.support.v4.app.Fragment gives an error - user208111
  • one
    @ user208111, this is because you have android.app.FragmentTransaction and getFragmentManager(); , but you need android.support.v4.app.FragmentTransaction and getSupportFragmentManager() - Vladyslav Matviienko
  • Thanks for the explanation, here I just getSupportFragmentManager() does not find if android.support.v4.app.FragmentTransaction - user208111
  • one
    @ user208111, it means that your Activity is inherited not from the one you need. - Vladyslav Matviienko