Home > OS >  How we can use intent for row items in android jetpack compose?
How we can use intent for row items in android jetpack compose?

Time:01-25

I start to learning jetpack compose in Android jetpack compose, I try to use intent for text menu items, I was saw many example for button on internet and in some books, but I want to use it for text row, I try to use below example, but app crashed, I do not know what I missed?

class MyActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyScreen()
        }
    }

}
@Composable
fun MyScreen(

) {

    val context = LocalContext.current


            Column(
                modifier = Modifier.fillMaxSize()
            ) {

               MainRow(

                   name = "Menu1",
                
                   context.startActivity(Intent(context, Menu1Activity::class.java))

               )

                MainRow(
                    name = "Menu2",
            
                    context.startActivity(Intent(context, Menu2Activity::class.java))
                )
          }
        }
@Composable
fun MainRow(
    name: String,
  
    startActivity: Unit

) {

        Row(
            modifier = Modifier
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {

           

            Text(
                text = name,
                style = TextStyle(
                    fontSize = 16.sp,
                    color = Color.Gray
                ),
            )

        }
    }

CodePudding user response:

@Composable
fun MainRow(
    name: String,  
    startActivity: **() -> Unit**
) {
        Row(
            modifier = Modifier**.clickable { startActivity() }**
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = name,
                style = TextStyle(
                    fontSize = 16.sp,
                    color = Color.Gray
                ),
            )
        }
    }

And call it like this:

MainRow(name = "Menu2", 
startActivity = **{**context.startActivity(Intent(context, Menu2Activity::class.java))**}**)
  •  Tags:  
  • Related