How can a tab system with navigation history be implemented without using fragments?
sobes.tech AI
Answer from AI
To implement a tab system with navigation history preservation without using fragments, several approaches can be used:
-
Using multiple Activities. Each tab is a separate Activity. When switching between tabs, the corresponding Activity is launched, and the navigation history within each Activity is maintained by the system.
-
ViewPager with ViewGroup and custom state management. Instead of fragments, you can use a ViewPager or a custom container, where each tab has its own View (e.g., a custom Layout). To preserve navigation history, you can store the stack of states within each View or use separate data structures.
-
Using Navigation Component with NavHostFragment replaced by a custom container — but this is closer to fragments.
-
Manually saving state. When switching tabs, save the current screen state (e.g., form data, scroll position) in a ViewModel or Bundle, and restore it upon return.
Example of a simple approach with View and ViewModel:
class TabManager {
private val tabStates = mutableMapOf<Int, Bundle>()
fun saveState(tabId: Int, state: Bundle) {
tabStates[tabId] = state
}
fun restoreState(tabId: Int): Bundle? {
return tabStates[tabId]
}
}
Thus, you can manually manage the state and navigation history without fragments, using ViewModel and custom Views for each tab.