Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack compose navigation architecture without fragment?

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()
        }
    }
}
like image 543
u2gilles Avatar asked Jan 02 '21 18:01

u2gilles


People also ask

Do you need fragments in Jetpack Compose?

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.

Do I need fragments with Compose?

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.

How do you prevent unnecessary Recompositions in Jetpack Compose?

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.


1 Answers

Yes, you are correct. Using no fragments is preferred. You can use a NavHost to declare your navigation graph.

like image 198
Noah Avatar answered Oct 13 '22 09:10

Noah