Search code examples
onclickandroid-jetpack

How do I add an OnClick to a LazyColumn text in Jetpack Compose?


I just made a LazyColumn and put texts, but to those texts I want to add an OnClick attribute so that when clicking on each text in the list it calls a different phone number. For example: I want if I press where it says "first" the app call a phone number (the number that I put in the code, I don't want it to call a number that I must put when I use the app), and if I press where it says "second" the app call another phone number. I am working with Jetpack Compose, can you help me please? This is what I did so far:

   @Composable
fun Hacerllamada(){
val intent = Intent (Intent.ACTION_CALL)
    intent.data = Uri.parse("tel: ")
}

@Preview
@Composable
fun Columna()  {
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Gray)
    ) {
        item{
        Text(
            text = "primero",
            fontSize = 32.sp,
            color = Color.White,
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center)

        Text(text = "segundo",
            fontSize = 32.sp,
            color = Color.White,
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center)

        Text(text = "tercero",
            fontSize = 32.sp,
            color = Color.White,
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center)}
    }
}

Solution

  • Your Hacerllamada() should not be a @Composable, just a normal method. Then you could add clickable to the modifier of your Text composable. Something like this

    fun makeACall(context: Context, phoneNumber: String) {
        val intent = Intent(Intent.ACTION_CALL)
        intent.data = Uri.parse("tel: $phoneNumber")
        //make sure you have permission to make a call
        startActivity(context, intent, bundleOf())
    }
    
    
    @Composable
    fun Columna() {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Gray)
        ) {
            item {
                PhoneNumber(title = "primero", phoneNumber = "11111")
                PhoneNumber(title = "segundo", phoneNumber = "22222")
                PhoneNumber(title = "tercero", phoneNumber = "33333")
            }
        }
    }
    
    @Composable
    fun PhoneNumber(title: String, phoneNumber: String) {
        val context = LocalContext.current
        Text(
            text = title,
            fontSize = 32.sp,
            color = Color.White,
            modifier = Modifier
                .fillMaxWidth()
                .clickable { makeACall(context = context, phoneNumber = phoneNumber) },
            textAlign = TextAlign.Center
        )
    }`enter code here`