Change alpha when Compose Surface is being pressed (clickable modifier) - android

I'm using the clickable modifier on Surface and want to create a custom indication to have the surface (along with its contents) appear with 0.5 alpha when being pressed. But it seems the indication can only be used to draw additional UI.
How do I redraw the Surface with 0.5 alpha when it is pressed?
Surface(
modifier = Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = CustomIndication, onClick = onClick)
) {
...
}

In the clickable modifier you can specify the Indication parameter. You can use the default ripple defined by rememberRipple changing the color.
Something like:
val interactionSource = remember { MutableInteractionSource() }
//clickable modifier
val clickable = Modifier.clickable(
interactionSource = interactionSource,
indication = rememberRipple(color = /* use you custom color */
MaterialTheme.colors.primary.copy(alpha = 0.5f))
) { /* update some business state here */ }
Surface(modifier = clickable){
//...
}
Otherwise you can use something like:
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val backgroundAlpha = if (isPressed) 0.5f else 1f
Surface(
modifier = Modifier.clickable(true){},
color= MaterialTheme.colors.secondary.copy(alpha = backgroundAlpha)
) {
//....
}

Try this:
var isPressed by remember { mutableStateOf(false) }
val backgroundAlpha = if (isPressed) 0.5f else 1f
Surface(
modifier = Modifier
.clickable { }
.pointerInput(Unit) {
detectTapGestures(
onPress = {
isPressed = true
val success = tryAwaitRelease()
if (success) isPressed = false
else isPressed = true
}
)
},
color = MaterialTheme.colors.primary.copy(alpha = backgroundAlpha)
) {
...
}

#Composable
fun AlphaSurface(){
val isClicked = remember { mutableStateOf(false) }
val alphaValue = if(isClicked.value) 0.5f else 1f
Surface(
modifier = Modifier.clickable {
isClicked.value = isClicked.value.not() // toggle the value
}.fillMaxHeight().fillMaxWidth(),
color = MaterialTheme.colors.primary.copy(alpha = alphaValue )
) {
}
}

Related

Bounce Button Animation in Compose

I want to make a button like this in Compose:
https://pub.dev/packages/flutter_bounceable
But the clickable method is not work in my code.
I tried with this code, but it has an error.
Pushing the button, but there's no action.
Animations are working well, but not for the clickable.
fun Modifier.bounceClick(onClick: () -> Unit,animationDuration: Int = 100,
scaleDown: Float = 0.9f) = composed {
val interactionSource = MutableInteractionSource()
val coroutineScope = rememberCoroutineScope()
val scale = remember {
Animatable(1f)
}
this
.scale(scale = scale.value)
.background(
color = Color(0xFF35898F),
shape = RoundedCornerShape(size = 12f)
)
.clickable(interactionSource = interactionSource, indication = null, onClick = onClick)
.pointerInput(Unit) {
while(true)
awaitPointerEventScope {
awaitFirstDown()
coroutineScope.launch {
scale.animateTo(
scaleDown,
animationSpec = tween(animationDuration),
)
}
waitForUpOrCancellation()
coroutineScope.launch {
scale.animateTo(
scaleDown,
animationSpec = tween(20),
)
scale.animateTo(
1f,
animationSpec = tween(animationDuration),
)
}
}
}
}
This is quite simple to do with Compose.
You should use foreachGesture or awaitEachGesture if Compose version is 1.4.0-alpha03 with Modifier.pointerInput instead of while. Also when you have clickable you don't need Modifier.pointerInput as well , you can use either of them.
I will only demonstrate how to do it with Modifier.clickable and interactionSource.collectIsPressedAsState() as below.
Result
Implementation
fun Modifier.bounceClick(
animationDuration: Int = 100,
scaleDown: Float = 0.9f,
onClick: () -> Unit
) = composed {
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val animatable = remember {
Animatable(1f)
}
LaunchedEffect(key1 = isPressed) {
if (isPressed) {
animatable.animateTo(scaleDown)
} else animatable.animateTo(1f)
}
Modifier
.graphicsLayer {
val scale = animatable.value
scaleX = scale
scaleY = scale
}
.clickable(
interactionSource = interactionSource,
indication = null
) {
onClick()
}
}
Usage
#Composable
private fun BounceExample() {
Row {
Box(
Modifier
.background(Color.Red, RoundedCornerShape(10.dp))
.bounceClick {
}
.padding(10.dp),
contentAlignment = Alignment.Center
) {
Text(text = "Hello World", color = Color.White, fontSize = 20.sp)
}
Spacer(modifier = Modifier.width(10.dp))
Box(
Modifier
.bounceClick {
}
.background(Color.Green, RoundedCornerShape(10.dp))
.padding(10.dp),
contentAlignment = Alignment.Center
) {
Text(text = "Hello World", color = Color.White, fontSize = 20.sp)
}
}
}

I cannot color single text from my list on click Jetpack Compose (single selection)

I have a string list of texts, when I click one of them I should color it in one color, currently my implementation colors all of the texts, what I'm doing wrong ?
var isPressed by remember { mutableStateOf(false) }
val buttonColor: Color by animateColorAsState(
targetValue = when (isPressed) {
true -> FreshGreen
false -> PastelPeach
},
animationSpec = tween()
)
LazyRow(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(25.dp)
) {
items(filterList) { filterName ->
Text(
text = filterName,
modifier = Modifier
.background(shape = RoundedCornerShape(24.dp), color = buttonColor)
.padding(horizontal = 16.dp, vertical = 8.dp)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null
) {
isPressed = !isPressed
onFilterClick(filterName)
}
)
}
}
You are using the same state (isPressed) for all the items.
As alternative to z.y's answer you can just move the isPressed declaration inside the items block:
LazyRow(
horizontalArrangement = Arrangement.spacedBy(25.dp)
) {
items(itemsList) { filterName->
var isPressed by remember { mutableStateOf(false) }
val buttonColor: Color by animateColorAsState(
targetValue = when (isPressed) {
true -> Color.Green
false -> Color.Red
},
animationSpec = tween()
)
Text(
//your code
)
}
}
For those who wants only to keep selected only one item at the time, here is the way I went for
#Composable
fun BrandCategoryFilterSection(
modifier: Modifier,
uiState: BrandFilterUiState,
onBrandCategoryClick: (String) -> Unit
) {
var selectedIndex by remember { mutableStateOf(-1) }
LazyRow(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(25.dp)
) {
itemsIndexed(uiState.categoryList) { index, categoryName ->
CategoryText(
categoryName = categoryName,
isSelected = index == selectedIndex,
onBrandCategoryClick = {
selectedIndex = index
onBrandCategoryClick(it)
}
)
}
}
}
#Composable
private fun CategoryText(categoryName: String, onBrandCategoryClick: (String) -> Unit, isSelected: Boolean) {
val buttonColor: Color by animateColorAsState(
targetValue = when (isSelected) {
true -> FreshGreen
false -> PastelPeach
},
animationSpec = tween()
)
Text(
text = categoryName,
modifier = Modifier
.background(shape = RoundedCornerShape(24.dp), color = buttonColor)
.padding(horizontal = 16.dp, vertical = 8.dp)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null
) {
onBrandCategoryClick(categoryName)
}
)
}
I modified your code, where I lowered down the animation and the pressed state so the parent composable won't suffer from its own re-composition
#Composable
fun MyScreen(
modifier: Modifier = Modifier,
filterList: SnapshotStateList<String>
) {
LazyRow(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(25.dp)
) {
items(filterList) { filterName ->
FilterText(
filterName
)
}
}
}
#Composable
fun FilterText(
filter: String
) {
var isPressed by remember { mutableStateOf(false) }
val buttonColor: Color by animateColorAsState(
targetValue = when (isPressed) {
true -> Color.Blue
false -> Color.Green
},
animationSpec = tween()
)
Text(
text = filter,
modifier = Modifier
.background(shape = RoundedCornerShape(24.dp), color = buttonColor)
.padding(horizontal = 16.dp, vertical = 8.dp)
.clickable {
isPressed = !isPressed
}
)
}

What is the difference between creating different animateColorAsState function vs a single updateTransition function?

Here is a function is which I create 2 different animationAsState function.
#Composable
fun AnimateAsStateDemo1() {
var boxState by remember {
mutableStateOf(false)
}
val color by animateColorAsState(
targetValue = if (boxState) Color.Blue else Color.Red,
)
val size by animateDpAsState(targetValue = if (boxState) 100.dp else 50.dp)
Box(
modifier = Modifier
.size(size = size)
.background(color = color)
.clickable {
boxState = !boxState
}
)
}
Here I create a single updateTransition transition to achieve the same result.
#Composable
fun AnimateAsStateDemo2() {
var boxState by remember {
mutableStateOf(false)
}
val transition = updateTransition(targetState = boxState, label = "")
val color by transition.animateColor(label = "") { state ->
when (state) {
true -> Color.Blue
false -> Color.Red
}
}
val size by transition.animateDp(label = "") { state ->
when (state) {
true -> 100.dp
false -> 50.dp
}
}
Box(
modifier = Modifier
.size(size = size)
.background(color = color)
.clickable {
boxState = !boxState
}
)
}
They both achieve the same result.
Is the second approach superior to the first approach? If so why?

How to bring a widget front when it is focused(or selected ) in jetpack compose

I have a page like this:
When one box is focused, it will be scaled. I use Modifier.graphicsLayer() to scale it.
but the scaled box will be covered by other boxes(box01 is covered by box02,box04 and box 05)
what I actually need is: the scaled box covers other boxes,like this:
My Sample Code:
#Composable
fun FocusBox(
title:String,
requester: FocusRequester = FocusRequester(),
modifier: Modifier = Modifier
) {
var boxColor by remember { mutableStateOf(Color.White) }
var scale by remember { mutableStateOf(1f) }
Box(
Modifier
.focusRequester(requester)
.onFocusChanged {
boxColor = if (it.isFocused) Color.Green else Color.Gray
scale = if (it.isFocused) { 1.3f } else { 1f }
}
.focusable()
.graphicsLayer(
scaleX = scale,
scaleY = scale
).background(boxColor)
) {
Text(
text = title,
modifier = Modifier.padding(30.dp),
color = Color.White,
style = MaterialTheme.typography.subtitle2
)
}
}
#Composable
fun FocusScaleBoxDemo(){
Row(modifier = Modifier.padding(30.dp)){
Column{
FocusBox(title = "Box_01")
Spacer(modifier = Modifier.padding(5.dp))
FocusBox(title = "Box_02")
Spacer(modifier = Modifier.padding(5.dp))
FocusBox(title = "Box_03")
Spacer(modifier = Modifier.padding(5.dp))
}
Spacer(modifier = Modifier.padding(5.dp))
Column{
FocusBox(title = "Box_04")
Spacer(modifier = Modifier.padding(5.dp))
FocusBox(title = "Box_05")
Spacer(modifier = Modifier.padding(5.dp))
FocusBox(title = "Box_06")
Spacer(modifier = Modifier.padding(5.dp))
}
}
}
Basically you need zIndex to bring view under neighbours. But this modifier only works for one container. So if you only add it to the selected box, neighbour column will still be on top of that. You need to add it to the Column containing selected box too.
I also prettified you code a little bit: try to avoid code repetition as much as possible - you'll decrease mistake chances and increase modifications speed
#Composable
fun FocusScaleBoxDemo() {
val columnsCount = 2
val rowsCount = 3
var focusedColumnIndex by remember { mutableStateOf(0) }
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.padding(30.dp)
) {
for (column in 0 until columnsCount) {
Column(
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier
.zIndex(if (column == focusedColumnIndex) 1f else 0f)
) {
for (row in 0 until rowsCount) {
val boxIndex = column * rowsCount + row
FocusBox(
title = "Box_${boxIndex + 1}",
onFocused = {
focusedColumnIndex = column
},
)
}
}
}
}
}
#Composable
fun FocusBox(
title: String,
onFocused: () -> Unit,
requester: FocusRequester = remember { FocusRequester() },
) {
var isFocused by remember { mutableStateOf(false) }
val scale = if (isFocused) 1.3f else 1f
Box(
Modifier
.focusRequester(requester)
.onFocusChanged {
isFocused = it.isFocused
if (isFocused) {
onFocused()
}
}
.focusable()
.graphicsLayer(
scaleX = scale,
scaleY = scale
)
.background(if (isFocused) Color.Green else Color.Gray)
.zIndex(if (isFocused) 1f else 0f)
) {
Text(
text = title,
modifier = Modifier.padding(30.dp),
color = Color.White,
style = MaterialTheme.typography.subtitle2
)
}
}

Scaling Button Animation in Jetpack Compose

I want to build this awesome button animation pressed from the AirBnB App with Jetpack Compose
Unfortunately, the Animation/Transition API was changed recently and there's almost no documentation for it. Can someone help me get the right approach to implement this button press animation?
Edit
Based on #Amirhosein answer I have developed a button that looks almost exactly like the Airbnb example
Code:
#Composable
fun AnimatedButton() {
val boxHeight = animatedFloat(initVal = 50f)
val relBoxWidth = animatedFloat(initVal = 1.0f)
val fontSize = animatedFloat(initVal = 16f)
fun animateDimensions() {
boxHeight.animateTo(45f)
relBoxWidth.animateTo(0.95f)
// fontSize.animateTo(14f)
}
fun reverseAnimation() {
boxHeight.animateTo(50f)
relBoxWidth.animateTo(1.0f)
//fontSize.animateTo(16f)
}
Box(
modifier = Modifier
.height(boxHeight.value.dp)
.fillMaxWidth(fraction = relBoxWidth.value)
.clip(RoundedCornerShape(8.dp))
.background(Color.Black)
.clickable { }
.pressIndicatorGestureFilter(
onStart = {
animateDimensions()
},
onStop = {
reverseAnimation()
},
onCancel = {
reverseAnimation()
}
),
contentAlignment = Alignment.Center
) {
Text(text = "Explore Airbnb", fontSize = fontSize.value.sp, color = Color.White)
}
}
Video:
Unfortunately, I cannot figure out how to animate the text correctly as It looks very bad currently
Are you looking for something like this?
#Composable
fun AnimatedButton() {
val selected = remember { mutableStateOf(false) }
val scale = animateFloatAsState(if (selected.value) 2f else 1f)
Column(
Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(
onClick = { },
modifier = Modifier
.scale(scale.value)
.height(40.dp)
.width(200.dp)
.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
selected.value = true }
MotionEvent.ACTION_UP -> {
selected.value = false }
}
true
}
) {
Text(text = "Explore Airbnb", fontSize = 15.sp, color = Color.White)
}
}
}
Here's the implementation I used in my project. Seems most concise to me.
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val sizeScale by animateFloatAsState(if (isPressed) 0.5f else 1f)
Button(
onClick = { },
modifier = Modifier
.wrapContentSize()
.graphicsLayer(
scaleX = sizeScale,
scaleY = sizeScale
),
interactionSource = interactionSource
) { Text(text = "Open the reward") }
Use pressIndicatorGestureFilter to achieve this behavior.
Here is my workaround:
#Preview
#Composable
fun MyFancyButton() {
val boxHeight = animatedFloat(initVal = 60f)
val boxWidth = animatedFloat(initVal = 200f)
Box(modifier = Modifier
.height(boxHeight.value.dp)
.width(boxWidth.value.dp)
.clip(RoundedCornerShape(4.dp))
.background(Color.Black)
.clickable { }
.pressIndicatorGestureFilter(
onStart = {
boxHeight.animateTo(55f)
boxWidth.animateTo(180f)
},
onStop = {
boxHeight.animateTo(60f)
boxWidth.animateTo(200f)
},
onCancel = {
boxHeight.animateTo(60f)
boxWidth.animateTo(200f)
}
), contentAlignment = Alignment.Center) {
Text(text = "Utforska Airbnb", color = Color.White)
}
}
The default jetpack compose Button consumes tap gestures in its onClick event and pressIndicatorGestureFilter doesn't receive taps. That's why I created this custom button
You can use the Modifier.pointerInput to detect the tapGesture.
Define an enum:
enum class ComponentState { Pressed, Released }
Then:
var toState by remember { mutableStateOf(ComponentState.Released) }
val modifier = Modifier.pointerInput(Unit) {
detectTapGestures(
onPress = {
toState = ComponentState.Pressed
tryAwaitRelease()
toState = ComponentState.Released
}
)
}
// Defines a transition of `ComponentState`, and updates the transition when the provided [targetState] changes
val transition: Transition<ComponentState> = updateTransition(targetState = toState, label = "")
// Defines a float animation to scale x,y
val scalex: Float by transition.animateFloat(
transitionSpec = { spring(stiffness = 50f) }, label = ""
) { state ->
if (state == ComponentState.Pressed) 1.25f else 1f
}
val scaley: Float by transition.animateFloat(
transitionSpec = { spring(stiffness = 50f) }, label = ""
) { state ->
if (state == ComponentState.Pressed) 1.05f else 1f
}
Apply the modifier and use the Modifier.graphicsLayer to change also the text dimension.
Box(
modifier
.padding(16.dp)
.width((100 * scalex).dp)
.height((50 * scaley).dp)
.background(Color.Black, shape = RoundedCornerShape(8.dp)),
contentAlignment = Alignment.Center) {
Text("BUTTON", color = Color.White,
modifier = Modifier.graphicsLayer{
scaleX = scalex;
scaleY = scaley
})
}
Here is the ScalingButton, the onClick callback is fired when users click the button and state is reset when users move their finger out of the button area after pressing the button and not releasing it. I'm using Modifier.pointerInput function to detect user inputs:
#Composable
fun ScalingButton(onClick: () -> Unit, content: #Composable RowScope.() -> Unit) {
var selected by remember { mutableStateOf(false) }
val scale by animateFloatAsState(if (selected) 0.7f else 1f)
Button(
onClick = onClick,
modifier = Modifier
.scale(scale)
.pointerInput(Unit) {
while (true) {
awaitPointerEventScope {
awaitFirstDown(false)
selected = true
waitForUpOrCancellation()
selected = false
}
}
}
) {
content()
}
}
OR
Another approach without using an infinite loop:
#Composable
fun ScalingButton(onClick: () -> Unit, content: #Composable RowScope.() -> Unit) {
var selected by remember { mutableStateOf(false) }
val scale by animateFloatAsState(if (selected) 0.75f else 1f)
Button(
onClick = onClick,
modifier = Modifier
.scale(scale)
.pointerInput(selected) {
awaitPointerEventScope {
selected = if (selected) {
waitForUpOrCancellation()
false
} else {
awaitFirstDown(false)
true
}
}
}
) {
content()
}
}
If you want to animated button with different types of animation like scaling, rotating and many different kind of animation then you can use this library in jetpack compose. Check Here

Categories

Resources