package com.example.nestednav
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_nav)
bottomNav.setupWithNavController(navController)
}
}
// HomeFragment.kt
package com.example.nestednav
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import android.widget.TextView
class HomeFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val textView = TextView(requireContext())
textView.text = "Home Screen"
textView.textSize = 24f
textView.textAlignment = View.TEXT_ALIGNMENT_CENTER
return textView
}
}
// ProfileFragment.kt
package com.example.nestednav
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import android.widget.TextView
class ProfileFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val textView = TextView(requireContext())
textView.text = "Profile Screen"
textView.textSize = 24f
textView.textAlignment = View.TEXT_ALIGNMENT_CENTER
return textView
}
}
// NotificationsFragment.kt
package com.example.nestednav
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import android.widget.TextView
class NotificationsFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val textView = TextView(requireContext())
textView.text = "Notifications Screen"
textView.textSize = 24f
textView.textAlignment = View.TEXT_ALIGNMENT_CENTER
return textView
}
}This solution sets up a main navigation graph with two destinations: HomeFragment and a nested navigation graph called SettingsNavGraph. The nested graph contains ProfileFragment and NotificationsFragment. The MainActivity hosts the NavHostFragment and connects it to a BottomNavigationView for switching between Home and Settings sections.
Each fragment displays a simple centered text label. The nested navigation graph allows navigating inside the Settings section without leaving the main graph. This structure keeps navigation organized and modular.