Hello everyone! I'm exploring ways to migrate old...
# compose
g
Hello everyone! I'm exploring ways to migrate old projects to use Compose, but, I have one question and I think you can help me. Let's assume that I have a project with many activities and fragments, but part of my project now uses a single activity and composable screens. Could I call an old Activity/Fragment inside a compose screen? I could call a compose screen inside an Activity/Fragment flow. If possible, how are you managing it?
s
Hi @Gustavo Barbosa Barreto I've done the same task earlier, In the first step I migrated my single activity to compose and then load all fragment to it without migrating them by adding them into a compose and using compose-nav for navigation through them. With
AndroidViewBinding
you can load fragments to a compose.
Copy code
@Composable
fun LoginFragmentViewBindingExample() {
    AndroidViewBinding(LoginViewBinding::inflate) {
        exampleView.setBackgroundColor(Color.GRAY)
    }
}
and then you can migrate each fragment one by one.
for more detail see this.
g
Oh, thanks @Saeed Darvish it's a great approach. How are you doing to navigate from an Activity/Fragment to a composable screen? Are you using some deeplink approach?
s
I used deeplinks , but I think it's possible to open activities inside NavHost, for example:
Copy code
NavHost(navController = navController, startDestination = "profile") {
    composable("profile") { Profile(/*...*/) }
    composable("loginActivity") { /* Start activity here* }
    /*...*/
}
g
Awesome, I'll try it. Thanks @Saeed Darvish.
🙌 1
e
And how do you handle guys the interactions with some components, like onClicks, for every screen? I am using a viewmodel for every fragment, and then I need to implement some functions to interact with the components that are currently in the fragment. Do you instantiate the viewmodels in the composable functions and you created functions inside it? Or you handle all this in the activity?
g
@Enol Simón in my opinion the best approach is to inject the ViewModel as a param to the composable function, considering which this ViewModel is related to that screen. I didn't understand the problem with the click, could you send us an example? In this code about ViewModel and Compose, I guess that you can see it better: • Github code: https://github.com/google-developer-training/basic-android-kotlin-compose-training[…]/main/app/src/main/java/com/example/unscramble/ui/GameScreen.kt • Codelabs: https://developer.android.com/codelabs/basic-android-kotlin-compose-viewmodel-and-state#0
e
Thank you for the response @Gustavo Barbosa Barreto! It’s just a bit more complicated for me because i am using multiplatform, that’s why I don’t have very clear how I can get the same approach having to use platform specific code