Fragment add or replace not working

android, android-fragments, java

Solution

The problem here is that you're mixing `android.support.v4.app.Fragment` and `android.app.Fragment`. You need to convert all uses to use the support library, which also means calling `getSupportFragmentManager()`.

Something like this, for example:

    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    ExampleFragments fragment = new ExampleFragments();
    fragmentTransaction.replace(R.id.frag, fragment);
    fragmentTransaction.commit();

It is important to note that the support library `Fragment` and the normal `Fragment` are NOT interchangeable. They achieve the same purpose, but they cannot be replaced with one another in code.

Problem

I'm using the code from this reference. When I put in that code in my program I get an error as seen in the picture below. Any reasons for the error? `The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, ExampleFragments)` Code from my main activity: ``` public void red(View view) { android.app.FragmentManager fragmentManager = getFragmentManager(); android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ExampleFragments fragment = new ExampleFragments(); fragmentTransaction.replace(R.id.frag, fragment); fragmentTransaction.commit(); } ``` ExampleFragments.java ``` package com.example.learn.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ExampleFragments extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.blue_pill_frag, container, false); } } ``` Here: ``` package com.example.learn.fragments; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; ```

Original source

Related problems