Middle
What does the Single Activity approach mean in Android development?
sobes.tech AI
Answer from AI
The Single Activity approach means that the application has only one Activity component, which acts as the main container. Navigation and display of different screens (user interfaces) within this Activity are implemented using Fragments or Views.
Advantages:
- Simplified architecture: Fewer
Activitycomponents make it easier to manage the lifecycle and state. - Improved navigation handling: It is more convenient to build navigation graphs between
Fragmentsusing the Jetpack Navigation Component. - Reduced overhead:
Activityis a heavy component; using a single one eases system workload.
Disadvantages:
- Complexity with deep links: Additional logic may be required to handle deep links within a single
Activity. - Less obvious responsibility separation: All
Fragmentsare within oneActivity, which can complicate code structure for large projects without clear module separation.
Example of using Navigation Component in Single Activity:
<!-- res/navigation/nav_graph.xml -->
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_graph"
app:startDestination="@id/mainFragment">
<fragment
android:id="@+id/mainFragment"
android:name="com.example.myapp.ui.main.MainFragment"
android:label="Main Fragment">
<action
android:id="@+id/action_mainFragment_to_detailFragment"
app:destination="@id/detailFragment" />
</fragment>
<fragment
android:id="@+id/detailFragment"
android:name="com.example.myapp.ui.detail.DetailFragment"
android:label="Detail Fragment" />
</navigation>
<!-- activity_main.xml -->
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_host_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/nav_graph"
app:defaultNavHost="true"/>
// MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Navigation component will manage fragment replacement
}
}
In this example, MainActivity contains a NavHostFragment, which manages the display of various Fragments defined in nav_graph.xml. Transitions between Fragments are performed using actions (action).