I know it's a closed topic, but I'd like to leave my example ..
We create the respective classes 'we create a total of 3' that inherit from Fragment 'android.app.Fragment'
with their respective method onCreateView
that point or inflate your container
return inflater.inflate(R.layout.example_fragment, container, false);
On the other hand, we have our main container that will be where the respective Fragment will be housed with an ID 'small_container'
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/contenedor_pequeno"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.diego3l.fragmentsdiego.MainActivity"
tools:layout_editor_absoluteY="81dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:text="Bienvenido Fragments!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/button"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:elegantTextHeight="true"
android:text="Quiero un fragment"
android:onClick="dameFragments"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</android.support.constraint.ConstraintLayout>
And on the other hand we have the main class that is in charge of exchanging the respective fragments, the 3 that we have, with the respective button, which will change with each press, with a simple variable counter.
public class MainActivity extends AppCompatActivity {
int contador = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void dameFragments(View view) {
ExampleFragment1 fragment1 = new ExampleFragment1();
ExampleFragment2 fragment2 = new ExampleFragment2();
ExampleFragment3 fragment3 = new ExampleFragment3();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//comenzamos transacción
if (contador == 0) {
fragmentTransaction.add(R.id.contenedor_pequeno, fragment1);
fragmentTransaction.commit();
contador++;
} else if (contador == 1){
fragmentTransaction.replace(R.id.contenedor_pequeno, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
contador++;
} else if (contador == 2){
fragmentTransaction.replace(R.id.contenedor_pequeno, fragment3);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
contador = 0;
}
}
}
And this is the look of the Fragments in our container