Thursday, November 4, 2021

jetpack compose - Double click listener

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.unit.dp


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedObjectState: Bundle?) {
        super.onCreate(savedObjectState)
        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold() {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = {
                        Text(
                            text = "Compose - Double click listener"
                        )
                    },
                    backgroundColor = Color(0xFF1ca9c9),
                )
            },
            content = { MainContent() },
            backgroundColor = Color(0xFFF3ebad)
        )
    }


    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    fun MainContent() {
        val message = remember { mutableStateOf("Click Action")}
        val shape = remember { mutableStateOf(RoundedCornerShape(24.dp))}

        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier.fillMaxSize().padding(12.dp)
        ) {
            Box(
                modifier = Modifier
                    .size(250.dp)
                    .clip(shape.value)
                    .background(SolidColor(Color(0xFFE1ae84)))
                    .combinedClickable(
                        enabled = true,
                        onClick = {
                          shape.value = RoundedCornerShape(24.dp)
                            message.value = "Clicked"
                        },
                        onDoubleClick = {
                            shape.value = CircleShape
                            message.value = "Double Clicked"
                        }
                    )
                    .padding(12.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = message.value,
                    style = MaterialTheme.typography.h5
                )
            }
        }
    }
}