Junior
How to connect multiple screens in an application?
sobes.tech AI
Answer from AI
NavComponent (navigation component) from Android Jetpack.
- Fragment Nav Component: For applications based on fragments. Defines a navigation graph with destinations (screens) and actions (transitions).
- Navigation Actions: Define how to move from one destination to another. They can contain arguments.
- Safe Args: Gradle plugin for generating code that ensures type-safe navigation with arguments.
- Navigation Graph: XML resource describing all destinations and their connections.
<!-- res/navigation/nav_graph.xml -->
<navigation 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/nav_graph"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.HomeFragment"
android:label="Home"
tools:layout="@layout/fragment_home">
<action
android:id="@+id/action_homeFragment_to_detailFragment"
app:destination="@id/detailFragment" />
</fragment>
<fragment
android:id="@+id/detailFragment"
android:name="com.example.DetailFragment"
android:label="Detail"
tools:layout="@layout/fragment_detail">
<argument
android:name="itemId"
app:argType="integer" />
</fragment>
</navigation>
// Transition using Safe Args
findNavController().navigate(HomeFragmentDirections.actionHomeFragmentToDetailFragment(itemId = 123))
Alternatives (less preferred):
- Intent: Classic way to transition between Activities. Less flexible and more complex to manage in complex scenarios.
- FragmentTransaction: For manual management of adding, removing, and replacing fragments. Requires more code and is prone to errors.
- Custom solutions: Own implementations of screen management, often unnecessarily complex.