Skip to content Skip to sidebar Skip to footer

Android Jetpack Compose Fragment Without Xml

Goodnight! I'm using drawerContent and navigationIcon to create the menu, but can I create a Fragment () without xml? in compose jetpack. If anyone has any references I would be gr

Solution 1:

With Compose you can try something different. You can navigate between composables using the Navigation component (currently in 1.0.0-alpha10)

Create a NavController with:

valnavController= rememberNavController()

and define a NavHost with the destinations:

NavHost(
    navController,
    startDestination = "entry1"
) {
    composable("entry1") { Entry1(..) }
    composable("entry2") { Entry2(..) }
    composable("entry3") { Entry3(..) }
}

To simplify the navigation just create a sealed class (it is not mandatory).

sealedclassScreen(val route: String, @StringRes val resourceId: Int) {
    objectEntry1 : Screen("entry1", R.string.entry1)
    objectEntry2 : Screen("entry2", R.string.entry2)
    objectEntry3 : Screen("entry3", R.string.entry3)
}

and change the NavHost to:

NavHost(
    navController,
    startDestination = Screen.Entry1.route
) {
    composable(Screen.Entry1.route) { Entry1(/*..*/) }
    composable(Screen.Entry2.route) { Entry2(/*..*/) }
    composable(Screen.Entry3.route) { Entry3(/*..*/) }
}

Now just use a Scaffold to create a drawerContent and navigationIcon to open the menu and navigate to the destination:

valnavController= rememberNavController()
val current by navController.currentBackStackEntryAsState()
valscaffoldState= rememberScaffoldState()
valscope= rememberCoroutineScope()

valitems= listOf(
    Screen.Entry1,
    Screen.Entry2,
    Screen.Entry3
)

Scaffold(
    scaffoldState = scaffoldState,
    drawerContent = {
        //val currentRoute = current?.arguments?.getString(KEY_ROUTE)valcurrentRoute= current?.destination?.route

        items.forEach { screen ->
            valselected= currentRoute == screen.route
            valselectedColor=if (selected) Color.Yellow else Color.Transparent
            Row(modifier = Modifier
                .fillMaxWidth()
                .height(32.dp)
                .background(selectedColor)
                .clickable {
                    scope.launch { scaffoldState.drawerState.close()}
                    navController.navigate(screen.route) {
                        popUpTo = navController.graph.startDestinationlaunchSingleTop=true
                    }
                }) {
                   Text(stringResource(screen.resourceId))
            }
        }
    },
    topBar = {
        TopAppBar(){
            IconButton(
                onClick = {
                    scope.launch { scaffoldState.drawerState.open() }
                }
            ) {
                Icon(Icons.Filled.Menu,"")
            }
        }
    },
    content = {
        NavHost(
            navController,
            startDestination = Screen.Entry1.route
        ) {
          composable(Screen.Entry1.route) { Entry1(/*..*/) }
          composable(Screen.Entry2.route) { Entry2(/*..*/) }
          composable(Screen.Entry3.route) { Entry3(/*..*/) }
        }
    }
)

where:

@ComposablefunEntry1(navigateTo: () -> Unit) {

    Column(){
         /*.....*/
    }
}

enter image description here

Solution 2:

It worked my class looked like this:

package com.example.quitanda

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Menu
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.*
import com.google.accompanist.coil.CoilImage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


classMainActivity : ComponentActivity() {
    privateval responseState = mutableStateOf("")

    overridefunonCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{
            MainContent()
        }
    }


    @ComposableprivatefunRecyclerView(){
        Text(text = responseState.value)

        LazyColumn(/*contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),*/
                modifier = Modifier.fillMaxSize()){
            for(i in0..50){
                item {
                    Text(text = "Categoria 2, categoria 1",fontSize = 15.sp,
                            color=Color.White,modifier= Modifier
                        .background(
                                colorResource(id = R.color.red)
                        )
                        .fillMaxWidth(100f))
                    Row(verticalAlignment = Alignment.CenterVertically,
                            modifier= Modifier
                                .padding(bottom = 8.dp)
                                .fillMaxWidth(100f)
                        ) {

                        Images("https://quitandadivino.com.br/_next/image?url=https%3A%2F%2Fapi.quitandadivino.com.br%2Fuploads%2Fabacaxi_perola_20afb6c700.jpg&w=300&q=75")

                        Column {
                            Text("Abacaxi",fontSize = 20.sp)
                            Text("Aprox. 0,185g/un",fontSize = 15.sp,color=Color.LightGray)
                            Text("R$ 120,00/UN",fontSize = 15.sp,color=Color.Red)
                            Text("R$ 120,00/KG",fontSize = 15.sp,color=Color.Red)
                        }

                        Column(modifier= Modifier
                            .fillMaxWidth(100f)
                            .padding(5.dp)
                           ,horizontalAlignment = Alignment.End) {
                            Button(
                                    onClick = {},
                                    colors = ButtonDefaults.buttonColors(
                                            backgroundColor = Color.Red,
                                            contentColor = Color.White)
                            ) {
                                Text(text = stringResource(id = R.string.comprar))
                            }
                        }
                    }

                    Text(text = " ",fontSize = 15.sp,
                            modifier = Modifier
                                .padding(bottom = 2.dp) // margin
                                .fillMaxWidth(100f)
                                .background(colorResource(id = R.color.red))
                        )

                }
            }
        }

    }

    privatefunonPressView(){
        Toast.makeText(this,"Testar",Toast.LENGTH_LONG).show();
    }

    @ComposableprivatefunImages(url:String){
        Card(
                modifier = Modifier
                    .size(110.dp)
                    .testTag("circle")
                    .fillMaxSize()
                    .clickable(onClick = { onPressView() })
                    .padding(10.dp),
                shape = CircleShape,
                elevation = 2.dp,
        ) {

            CoilImage(
                    data = url,
                    contentDescription = "Abacaxi",
                    fadeIn = true
            )
        }
    }

    @ComposableprivatefunMainContent(){
        val scaffoldState = rememberScaffoldState()
        val scope = rememberCoroutineScope()
        val navController = rememberNavController()

         Scaffold(
                topBar = {
                    TopBar(scope,scaffoldState)
                         },
                content={

                    NavHost(
                            navController,
                            startDestination = Screen.Entry1.route
                    ) {
                        composable(Screen.Entry1.route) { Entry1() }
                        composable(Screen.Entry2.route) { Entry2() }
                        composable(Screen.Entry3.route) { Entry3() }
                    }
                },
                floatingActionButton = { MainFab() },
                drawerContent = {
                    DrawerContent(scope,scaffoldState,navController)
                },
                scaffoldState = scaffoldState
        )
    }


    @ComposableprivatefunDrawerContent(scope: CoroutineScope,scaffoldState:ScaffoldState
    ,navController: NavController
    ){

        val items = listOf(
                Screen.Entry1,
                Screen.Entry2,
                Screen.Entry3
        )

        Text("Drawer content", style = MaterialTheme.typography.h5)

        items.forEach { screen ->
            Row(modifier = Modifier
                .fillMaxWidth()
                .height(32.dp)
                .clickable {
                    scope.launch { scaffoldState.drawerState.close() }
                    navController.navigate(screen.route) {
                        popUpTo = navController.graph.startDestination
                        launchSingleTop = true
                    }
                }) {
                Text(stringResource(screen.resourceId))
            }
        }
    }

    @ComposableprivatefunTopBar(scope: CoroutineScope,scaffoldState:ScaffoldState){
        TopAppBar(title={
            Text(text = stringResource(id = R.string.app_name))
        },
                backgroundColor = colorResource(id = R.color.green),
                contentColor = Color.White,
                navigationIcon ={
                    IconButton(
                            onClick = {scope.launch { scaffoldState.drawerState.open() } }
                    ) {
                        Icon(imageVector = Icons.Default.Menu, contentDescription ="Menu" )
                    }
                }
        )
    }

    @ComposableprivatefunMainFab() {
        FloatingActionButton(onClick = {showAddForm()}) {
            Icon(imageVector = Icons.Filled.Add, contentDescription = "Adicionar")
        }
    }

   privatevar resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            // There are no request codesval response = result.data?.getParcelableExtra<AddUserState>("user_state")
            responseState.value = response.toString()
        }
    }

    privatefunshowAddForm() {
        val intent = Intent(this, FormActivity::class.java)
        resultLauncher.launch(intent)
    }

    @ComposableprivatefunEntry1(){
        Text(text = stringResource(id = R.string.entry1))
        RecyclerView()
    }

    @ComposableprivatefunEntry2(){
        Text(text = stringResource(id = R.string.entry2))
    }

    @ComposableprivatefunEntry3(){
        Text(text = stringResource(id = R.string.entry3))
    }
}

@Gabriele Mariotti Thank you very much

Post a Comment for "Android Jetpack Compose Fragment Without Xml"