I am a bit confused about the new Jetpack compose navigation component androidx.navigation:navigation-compose documented at https://developer.android.com/jetpack/compose/navigation.
Am I right to say that the single-activity architecture with 0 fragment is preferred to the single-activity architecture with multiple fragments when using Jetpack Compose ?
I know we can still use fragments and Jetpack compose in this manner :
class MyFragment: Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply{
setContent {
MyFragmentComposable()
}
}
}
}
But I want to make sure that when using androidx.navigation:navigation-compose, we are not supposed to use fragment anymore, starting like so:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp()
}
}
}
Or you might consider using fragments you are really unsatisfied with Jetpack Compose navigation and would like to continue using Android Navigation components. You need fragments as its lifecycle aware. Android already have custom view but you need lifecycle to efficiently manage view state.
In most use cases, you shouldn't need fragments at all if you are starting a pure compose screen/app. Moreover, since there are millions of apps that still use Fragments, there will most likely be ways to use it with that, although definitely not a requirement.
The solution here is to provide item keys. Providing a stable key for each item lets Compose avoid unnecessary recompositions. In this case, Compose can see that the item now at spot 3 is the same item that used to be at spot 2. Since none of the data for that item has changed, Compose doesn't have to recompose it.
Yes, you are correct. Using no fragments is preferred. You can use a NavHost
to declare your navigation graph.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With