Fragments in Android Studio: Create and Switch Fragments (Java)
Learn fragments: reusable pieces of a screen that you can swap in and out. Build an activity that switches between fragments with buttons.
What you'll learn
- Create fragments and their layouts
- Add and replace fragments with FragmentManager
- Switch fragments with buttons
- Understand the fragment lifecycle
Before you start
- Android Studio (any recent version)
- Basic Java: variables, methods and if/else
- An emulator or an Android phone
How it fits together
- 1MainActivity
- 2FragmentContainerView
- 3FirstFragment or SecondFragment
- 4Back returns to the previous one
Build it step by step
1. Create the project
In Android Studio choose New Project → Empty Views Activity, with Language Java and Minimum SDK API 24.
2. Make room for fragments
In activity_main.xml, add a FragmentContainerView with the ID fragment_container. Fragments appear inside it. Below it, add two buttons: First and Second.
3. Create the first fragment
A fragment is a reusable piece of a screen, with its own layout. Create fragment_first.xml, then a FirstFragment class that extends Fragment and passes the layout to the constructor: super(R.layout.fragment_first). That's the whole class.
4. Create the second fragment
SecondFragment has its own button and counter. Find its views in onViewCreated, the fragment's version of an activity's onCreate.
5. Show the first fragment on launch
In MainActivity.onCreate, use getSupportFragmentManager().beginTransaction() to add the first fragment. Only do this when savedInstanceState is null; after a rotation, Android restores the fragment for you.
6. Swap fragments
When a button is tapped, replace the fragment in the container. addToBackStack(null) remembers the swap, so Back returns to the previous fragment. setCustomAnimations adds a fade.
7. Say "1 time", not "1 times"
The counter uses a plurals resource with one and other forms, read with getQuantityString. Android picks the right form for the number and the language.
8. Run it
Tap Second, tap the button a few times, then press Back to return to the first fragment.
If something goes wrong
- Two fragments on top of each other after rotating: only add the first fragment when
savedInstanceState == null. - Back closes the app instead of going back: add
addToBackStack(null)to the transaction.
What's improved over the video
It uses FragmentContainerView, the layout-constructor shortcut, Back-stack support, fade animations and plurals.
Files affected
Check what to add and what to replace before copying code.
- app/src/main/java/com/example/fragments/MainActivity.javaReplace file
- app/src/main/res/layout/activity_main.xmlReplace file
- app/src/main/java/com/example/fragments/FirstFragment.javaAdd these lines
- app/src/main/res/layout/fragment_first.xmlAdd these lines
- app/src/main/res/layout/fragment_second.xmlAdd these lines
- app/src/main/java/com/example/fragments/Screens.javaAdd these lines
- app/src/main/java/com/example/fragments/SecondFragment.javaAdd these lines
- app/src/main/res/values/strings.xmlReplace file
Application code
Select a file to see its code and where it belongs.
This code uses package com.example.fragments. Change that first line to your own package, the one at the top of your MainActivity.
app/src/main/java/com/example/fragments/MainActivity.javaAdds the first fragment, and swaps fragments when the buttons are tapped.
package com.example.fragments;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
/** One screen with a container that shows either FirstFragment or SecondFragment. */
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Screens.setUp(this, R.layout.activity_main);
Button first = findViewById(R.id.btnFirst);
Button second = findViewById(R.id.btnSecond);
first.setOnClickListener(v -> show(new FirstFragment()));
second.setOnClickListener(v -> show(new SecondFragment()));
// Only add the first fragment on a fresh start. After rotation, Android restores the one on screen.
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_container, new FirstFragment())
.commit();
}
}
/** Swap the fragment in the container. addToBackStack lets Back return to the previous one. */
private void show(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
}


