Is it possible to navigate from a composable screen to a Fragment in Android?

91 views Asked by At

I just started working at a new company and their code base is a mix of XML and Jetpack compose. I need to implement navigation from a main screen to a settings screen but one screen is 100% compose while the other is a composable function hosted by a fragment which also has some compose code in the fragment class itself.

This is the whole setup:

An activity calls a composable function in its onCreate()

This composable function is said main screen which has its own Nav graph

From this composable, I need to navigate to a fragment that holds another nav graph and compose screen

The way I see it, there is no way to do this other than to rewrite the fragment as a composable screen since you cant use compose navigation to navigate to fragments / activities as far as I know.

Any pointers would be appreciated

1

There are 1 answers

0
Hiren Rafaliya On BEST ANSWER

Compose Nav graph will only support screens which are composable functions. We can't use fragments/activities with Nav graph to navigate.

Instead of using navgraph, pass a lambda function to the parameter of the initial composable function for navigation.

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // Pass a lambda function here
            MainNavGraph(onNavigate = {
                // Navigate to the activity/fragment from here
            })
        }
    }
    
    @Composable
    fun MainNavGraph(onNavigate: () -> Unit) {
       
        // Invoke lambda as per the logic
        onNavigate.invoke()
    }

}