Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Week 5 Lab 5 – Bottom Navigation Using Fragments Inside a Single Host Activity
Week 5 – Windows Mobile, Eclipse and Fragments · 150 min read · 11 MCQs to check yourself
Bottom Navigation View with fragments (Navigation component)
Objective
Build a dashboard with a BottomNavigationView that switches between three fragments – Home, Courses and Profile – inside one host activity, and pass the student's name to the Profile fragment. CLOs: CLO-2 (develop apps with fragments), CLO-1 (fragment architecture and lifecycle).
What you will build in CampusMate
A new screen HomeActivity (the dashboard), opened from the sign-in screen of Lab 4:
HomeActivity
┌────────────────────────────┐
│ fragment_container │ ← HomeFragment / CoursesFragment / ProfileFragment
│ │
├────────────────────────────┤
│ 🏠 Home 📚 Courses 👤 Profile │ ← BottomNavigationView
└────────────────────────────┘
Workflow
| Step | What you do | File |
|---|---|---|
| 1 | Create 3 fragments (class + layout) | New → Fragment → Fragment (Blank) |
| 2 | Add 3 tab icons | New → Vector Asset |
| 3 | Create the tab menu | res/menu/bottom_nav_menu.xml |
| 4 | Create the host activity | HomeActivity + activity_home.xml |
| 5 | Switch fragments on tab click | HomeActivity.java |
| 6 | Pass the name to ProfileFragment | Bundle arguments |
| 7 | Open the dashboard from Lab 4's screen | MainActivity.java |
| 8 | Run, rotate and test | Emulator |
Step 1 – Create the three fragments
For each fragment: right-click the package → New → Fragment → Fragment (Blank) → names HomeFragment, CoursesFragment, ProfileFragment, Language Java.
The wizard generates a lot of template code – replace each class with the short version below.
res/layout/fragment_home.xml (make the other two the same, changing the text and ids):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home – Today at campus"
android:textSize="22sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnHello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Show today's notice" />
</LinearLayout>
fragment_courses.xml → a TextView tvCourses with text "CDE-315 Mobile App Development\nCS-301 Artificial Intelligence\nGEN-103 ICT".
fragment_profile.xml → a TextView tvProfile with text "Profile".
HomeFragment.java
package com.example.campusmate;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
public HomeFragment() {
super(R.layout.fragment_home); // the fragment inflates this layout automatically
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Find views with view.findViewById(...) – a fragment is not an Activity
view.findViewById(R.id.btnHello).setOnClickListener(v ->
Toast.makeText(requireContext(), "MAD lab at 10:00 am in Lab 2", Toast.LENGTH_SHORT).show());
}
}
CoursesFragment.java
public class CoursesFragment extends Fragment {
public CoursesFragment() {
super(R.layout.fragment_courses);
}
}
ProfileFragment.java (reads the name from its arguments – Step 6)
public class ProfileFragment extends Fragment {
public ProfileFragment() {
super(R.layout.fragment_profile);
}
// Factory method: the correct way to give data to a fragment
public static ProfileFragment newInstance(String name) {
ProfileFragment f = new ProfileFragment();
Bundle args = new Bundle();
args.putString("NAME", name);
f.setArguments(args);
return f;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String name = (getArguments() != null) ? getArguments().getString("NAME", "Student") : "Student";
TextView tvProfile = view.findViewById(R.id.tvProfile);
tvProfile.setText("Profile of " + name);
}
}
(Add the imports Android Studio suggests with Alt+Enter.)
Step 2 – Tab icons
Right-click res → New → Vector Asset → Clip art → search home → name ic_home → Finish. Repeat for menu_book (ic_courses) and person (ic_profile).
Step 3 – The tab menu (res/menu/bottom_nav_menu.xml)
Right-click res → New → Android Resource File → type Menu, name bottom_nav_menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/nav_home" android:icon="@drawable/ic_home" android:title="Home" />
<item android:id="@+id/nav_courses" android:icon="@drawable/ic_courses" android:title="Courses" />
<item android:id="@+id/nav_profile" android:icon="@drawable/ic_profile" android:title="Profile" />
</menu>
Step 4 – The host activity
New → Activity → Empty Views Activity → HomeActivity (Java). activity_home.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_nav_menu" />
</LinearLayout>
BottomNavigationView comes from the Material Components library, which is already in new projects.
Step 5 – HomeActivity.java: switch fragments
package com.example.campusmate;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class HomeActivity extends AppCompatActivity {
private String studentName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
studentName = getIntent().getStringExtra("NAME"); // sent from MainActivity (Step 7)
if (studentName == null) studentName = "Student";
BottomNavigationView bottomNav = findViewById(R.id.bottomNav);
bottomNav.setOnItemSelectedListener(item -> {
int id = item.getItemId();
if (id == R.id.nav_home) {
showFragment(new HomeFragment());
} else if (id == R.id.nav_courses) {
showFragment(new CoursesFragment());
} else if (id == R.id.nav_profile) {
showFragment(ProfileFragment.newInstance(studentName));
}
return true; // true = mark this tab as selected
});
// Show Home only the FIRST time. After rotation the FragmentManager
// restores the current fragment by itself.
if (savedInstanceState == null) {
showFragment(new HomeFragment());
}
}
private void showFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.replace(R.id.fragment_container, fragment) // swap the content area
.commit();
}
}
Step 6 – How the name reaches ProfileFragment
ProfileFragment.newInstance(studentName) puts the name into the fragment's arguments Bundle; the fragment reads it in onViewCreated with getArguments().getString("NAME"). Arguments survive rotation – a public static variable would not be safe.
Step 7 – Open the dashboard from the sign-in screen
In Lab 4's MainActivity.openProfile() you can now start the dashboard instead of (or in addition to) SecondActivity. Add a Button btnDashboard ("Open dashboard") to activity_main.xml and in onCreate:
findViewById(R.id.btnDashboard).setOnClickListener(v -> {
Intent i = new Intent(MainActivity.this, HomeActivity.class);
i.putExtra("NAME", etName.getText().toString().trim());
startActivity(i);
});
Step 8 – Watch the fragment lifecycle (optional)
Add Log.d("FRAG", "Courses onViewCreated") in a fragment and onDestroyView() with a log; switching tabs shows the old fragment being destroyed and the new one created, because replace() removes the old one.
Run and test
| Test | Expected result |
|---|---|
| Enter name "Ali" → Open dashboard | Home tab selected, Home text visible |
| Tap Show today's notice | Toast "MAD lab at 10:00 am in Lab 2" |
| Tap Courses | Course list shown |
| Tap Profile | "Profile of Ali" |
| Rotate on Profile | Still Profile – no duplicate Home on top |
Common errors and fixes
| Problem | Fix |
|---|---|
| Two fragments drawn on top of each other after rotation | Show the first fragment only if (savedInstanceState == null) |
findViewById red in a fragment |
Use view.findViewById(...) inside onViewCreated |
| Toast error in a fragment | Use requireContext() instead of this |
| Icons missing | Check android:icon="@drawable/ic_home" names match the Vector Asset names |
Short and long questions
1. (Viva) Why is a single-activity app with fragments preferred for bottom navigation?
Model answer
The bottom bar stays in one host activity while only the content area changes, which is faster and smoother than starting new activities; fragments are reusable, share the activity's ViewModel and are restored automatically on rotation.
2. (Viva) What happened in Logcat when you switched tabs?
Model answer
The old fragment's onPause/onStop/onDestroyView/onDestroy were called (because replace removed it) and the new fragment ran onAttach/onCreate/onCreateView/onViewCreated/onStart/onResume.
3. (Viva) How are the tabs of a BottomNavigationView defined and handled?
Model answer
Tabs are items (id, icon, title) in a menu resource referenced by app:menu; in code setOnItemSelectedListener checks item.getItemId() and replaces the fragment in the container, returning true.
4. (Viva) Write the transaction used to show a fragment in the container.
Model answer
getSupportFragmentManager().beginTransaction().setReorderingAllowed(true).replace(R.id.fragment_container, new CoursesFragment()).commit();
This lesson ends with a quiz of 11 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Week 5 Theory – Application Development with Windows Mobile; Eclipse; Fragments · Next: Week 6 Theory – Calling Built-in Applications Using Intents; Displaying Notifications
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester