therealccarter therealccarter - 6 months ago 29
Android Question

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

Relevant code:

addDay.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
++fragIdCount;
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(R.id.templateFragmentLayout, frag2, fragString); // "frag2" is where the error is
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
}
});


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

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

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