How to use Compose inside Fragment? How to use Compose inside Fragment? android android

How to use Compose inside Fragment?


setContent on ViewGroup is now deprecated.

The below is accurate as of Compose v1.0.0-alpha01.

For pure compose UI Fragment:

class ComposeUIFragment : Fragment() {    override fun onCreateView(        inflater: LayoutInflater, container: ViewGroup?,        savedInstanceState: Bundle?    ): View? {        return ComposeView(requireContext()).apply {            setContent {                Text(text = "Hello world.")            }        }    }}

For hybrid compose UI Fragment - add ComposeView to xml layout, then:

class ComposeUIFragment : Fragment() {    override fun onCreateView(        inflater: LayoutInflater, container: ViewGroup?,        savedInstanceState: Bundle?    ): View? {        return inflater.inflate(R.layout.fragment_compose_ui, container, false).apply {            findViewById<ComposeView>(R.id.composeView).setContent {                Text(text = "Hello world.")            }        }    }}


Found it:

class LoginFragment : Fragment() {override fun onCreateView(    inflater: LayoutInflater, container: ViewGroup?,    savedInstanceState: Bundle?): View? {    // Inflate the layout for this fragment    val fragmentView = inflater.inflate(R.layout.fragment_login, container, false)    (fragmentView as ViewGroup).setContent {        Hello("Jetpack Compose")    }    return fragmentView}@Composablefun Hello(name: String) = MaterialTheme {    FlexColumn {        inflexible {            // Item height will be equal content height            TopAppBar( // App Bar with title                title = { Text("Jetpack Compose Sample") }            )        }        expanded(1F) {            // occupy whole empty space in the Column            Center {                // Center content                Text("Hello $name!") // Text label            }        }    } }}


You don't need Fragments with Compose. You can navigate to another screen without needing a Fragment or an Activity:

class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContent {            val navController = rememberNavController()            NavHost(navController, startDestination = "welcome") {                composable("welcome") { WelcomeScreen(navController) }                composable("secondScreen") { SecondScreen() }            }        }    }}@Composablefun WelcomeScreen(navController: NavController) {    Column {        Text(text = "Welcome!")        Button(onClick = { navController.navigate("secondScreen") }) {            Text(text = "Continue")        }    }}@Composablefun SecondScreen() {    Text(text = "Second screen!")}