therealccarter therealccarter - 1 year ago 104
Android Question

FragmentTransaction .add() argument giving "requires Fragment" error even though argument is a fragment

Relevant code:

addDay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
String fragString = Integer.toString(fragIdCount);
TemplateFragment1 frag2 = new TemplateFragment1(); // creating new fragment frag2 of fragment TemplateFragment1
fragmentTransaction.add(, frag2, fragString); // "frag2" is where the error is

TemplateFragment1 is a fragment. I'm creating a new variable that is a new TemplateFragment1 fragment. When I pass that in (frag2), I get an error saying that it requires a fragment there, but frag2 is a fragment! It's strange because I have this structure elsewhere in my program that works fine.

Edit: I did some research and I don't know why I was using the support fragment, but now I know better!

Answer Source

Your TemplateFragment1 probably extends (check the imports in that class), and you're using getFragmentManager method which takes the parameter of type, which is not the same as the one from support library.

Either change the method to getSupportFragmentManager or theTemplateFragment1 to extend the appropriate Fragment,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download