Thursday, April 15, 2021

jetpack compose - AnimateOffsetAsState

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Circle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val isEnabled = remember { mutableStateOf(true) }
        val isTop = remember { mutableStateOf(true) }

        val offset: Offset by animateOffsetAsState(
            targetValue = if (isTop.value)
                Offset(0f, 0f) else Offset(100f, 300f),
            animationSpec = tween(
                durationMillis = 2000, // duration
                easing = FastOutSlowInEasing
            ),
            finishedListener = {
                // disable the button
                isEnabled.value = true
            }
        )

        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFFCCCCFF))
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Button(
                onClick = {
                    isTop.value = !isTop.value
                    isEnabled.value = false
                },
                colors = ButtonDefaults.buttonColors(
                    Color(0xFF32127A), Color(0xCCFFFFFF)
                ),
                enabled = isEnabled.value
            ) {
                Text(
                    text = "Animate Offset Change",
                    modifier = Modifier.padding(12.dp)
                )
            }

            Icon(
                Icons.Filled.Circle,
                contentDescription = "Localized description",
                Modifier
                    .size(150.dp)
                    .offset(offset.x.dp, offset.y.dp),
                tint = Color(0xFF000080)
            )
        }
    }



    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}