mohamad mohamad - 6 months ago 30
Android Question

Inflating fragment from an activity

I wanna inflate some fragment from an activity (which is not main but is activity).

I do exactly like this instruction:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();

YourFragment fragment = new YourFragment();
fragmentTransaction.replace(android.R.id.content, fragment);//here is the error
fragmentTransaction.commit();


but in the one before last line, editor shows error saying:





2nd argument wrong type.Found:max.mzf.max.fragment.Required:android.app.fragment





this is my own code:

Activity

public class QuizCard extends FragmentActivity {

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_card);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
QcardFragment fragment = new QcardFragment();
fragmentTransaction.replace(R.id.your_placeholder, fragment );
fragmentTransaction.commit();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.card_menu, menu);

return true;
}





and this is QcardFragment:




public class QcardFragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get data from Argument
}
public void onCardClick(View view) {
flipCard();
}
private void flipCard() {
View rootLayout = (View) getActivity().findViewById(R.id.main_activity_root);
View cardFace = (View) getActivity().findViewById(R.id.main_activity_card_face);
View cardBack = (View) getActivity().findViewById(R.id.main_activity_card_back);

FlipAnimation flipAnimation = new FlipAnimation(cardFace, cardBack);

if (cardFace.getVisibility() == View.GONE) {
flipAnimation.reverse();
}
rootLayout.startAnimation(flipAnimation);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.qcardfragment, container, false);

}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);


}
}





What's wrong?

Answer

Make sure that your fragment class extends Fragment from android native library. If you are using external implementation try to change

FragmentManager fragmentManager = getFragmentManager();

to

 FragmentManager fragmentManager = getSupportFragmentManager();
Comments