Jetpack compose remember function not working - kotlin

I'm trying to create a scrollable background in Jetpack Compose.
The problem is that the variable "currentPadding" isn't updating it's state after the value "padding" is modified after recomposition. In the first composition (loading state) the "padding" value is set to 112.dp and after load the value changes to 160.dp.
It's strange because I have used the remember function this way multiple times in other places in the app and it's the first time that this happens.
Could you help me out?
Thanks a lot.
#Composable
fun ScrollableBackground(
scrollState: ScrollState,
composable: ComposableFun,
modifier: Modifier = Modifier,
isBannerListEmpty: Boolean,
) {
val padding = if (isBannerListEmpty) {
112.dp
} else {
160.dp
}
val minPadding: Dp = 29.dp
val dp0 = dimensionResource(id = R.dimen.no_dp)
var currentPadding: Dp by remember { mutableStateOf(padding) }
val state: Dp by animateDpAsState(targetValue = currentPadding)
val nestedScrollConnection: NestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val percent = scrollState.value.toFloat() / scrollState.maxValue.toFloat() * 100f
val delta = available.y.dp
val newSize = currentPadding + delta / 3
currentPadding = when {
percent > 20f -> minPadding
newSize < minPadding -> minPadding
newSize > padding -> padding
else -> newSize
}
return Offset.Zero
}
}
}
Box(
modifier = modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
) {
Surface(
color = White,
modifier = Modifier
.padding(top = state)
.fillMaxSize()
.clip(
CircleShape.copy(
topStart = Shapes.medium.topStart,
topEnd = Shapes.medium.topEnd,
bottomEnd = CornerSize(dp0),
bottomStart = CornerSize(dp0)
)
)
) {}
composable.invoke()
}
}
I tried sending other kind of parameters from the view model to the composable (instead of a boolean, in this case "isBannerListEmpty"), like the current desired padding value, and nothing seems to work.

You have put nestedScrollConnection in remember. It also remembers the padding variable when first encountered. So when the actual value of padding is changed, this change is not propagated in remember of nestedScrollConnection.
Put padding inside onPreScroll.
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val padding = if (...) { //Don't use isBannerListEmpty here as neither this will update on recomposition
112.dp
} else {
160.dp
}
...

Related

Change the width of Tab in Jetpack Compose ScrollableTabRow

I want to modify the width of each Tab, but I can't do it.
I know it can be customized, but I just want to modify the width, is there any way?
#OptIn(ExperimentalPagerApi::class)
#Preview
#Composable
fun TabPreviewTest() {
val scope = rememberCoroutineScope()
val colorScheme = MaterialTheme.colorScheme
val pagerState = rememberPagerState(initialPage = 1)
val titleList = rememberSaveable { mutableListOf("关注", "推荐", "美食", "护肤", "穿搭", "健身塑形", "数码") }
ScrollableTabRow(
selectedTabIndex = pagerState.currentPage,
containerColor = colorScheme.surface.copy(0.94f),
contentColor = colorScheme.primary,
divider = { DividerView(start = 0) }) {
titleList.forEachIndexed { index, title ->
Tab(text = { Text(text = title) },
selected = pagerState.currentPage == index,
selectedContentColor = colorScheme.primary,
unselectedContentColor = colorScheme.gray,
onClick = {
scope.launch { pagerState.scrollToPage(index) }
//onClick(index)
},
modifier = Modifier.padding(0.dp).width(0.dp)
)
}
}
}
You can change Tab width when it's above 90.dp since in source code it's measured with Cosntraints with minimum 90.dp
private val ScrollableTabRowMinimumTabWidth = 90.dp
in SubComposeLayout
#Composable
#UiComposable
fun ScrollableTabRow(
selectedTabIndex: Int,
modifier: Modifier = Modifier,
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
edgePadding: Dp = TabRowDefaults.ScrollableTabRowPadding,
indicator: #Composable #UiComposable
(tabPositions: List<TabPosition>) -> Unit = #Composable { tabPositions ->
TabRowDefaults.Indicator(
Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex])
)
},
divider: #Composable #UiComposable () -> Unit =
#Composable {
TabRowDefaults.Divider()
},
tabs: #Composable #UiComposable () -> Unit
) {
Surface(
modifier = modifier,
color = backgroundColor,
contentColor = contentColor
) {
val scrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val scrollableTabData = remember(scrollState, coroutineScope) {
ScrollableTabData(
scrollState = scrollState,
coroutineScope = coroutineScope
)
}
SubcomposeLayout(
Modifier.fillMaxWidth()
.wrapContentSize(align = Alignment.CenterStart)
.horizontalScroll(scrollState)
.selectableGroup()
.clipToBounds()
) { constraints ->
val minTabWidth = ScrollableTabRowMinimumTabWidth.roundToPx()
val padding = edgePadding.roundToPx()
// 🔥🔥 This is the minimum size it's measured with
val tabConstraints = constraints.copy(minWidth = minTabWidth)
val tabPlaceables = subcompose(TabSlots.Tabs, tabs)
.map { it.measure(tabConstraints) }
var layoutWidth = padding * 2
var layoutHeight = 0
tabPlaceables.forEach {
layoutWidth += it.width
layoutHeight = maxOf(layoutHeight, it.height)
}
// Position the children.
layout(layoutWidth, layoutHeight) {
// Place the tabs
val tabPositions = mutableListOf<TabPosition>()
var left = padding
tabPlaceables.forEach {
it.placeRelative(left, 0)
tabPositions.add(TabPosition(left = left.toDp(), width = it.width.toDp()))
left += it.width
}
// The divider is measured with its own height, and width equal to the total width
// of the tab row, and then placed on top of the tabs.
subcompose(TabSlots.Divider, divider).forEach {
val placeable = it.measure(
constraints.copy(
minHeight = 0,
minWidth = layoutWidth,
maxWidth = layoutWidth
)
)
placeable.placeRelative(0, layoutHeight - placeable.height)
}
// The indicator container is measured to fill the entire space occupied by the tab
// row, and then placed on top of the divider.
subcompose(TabSlots.Indicator) {
indicator(tabPositions)
}.forEach {
it.measure(Constraints.fixed(layoutWidth, layoutHeight)).placeRelative(0, 0)
}
scrollableTabData.onLaidOut(
density = this#SubcomposeLayout,
edgeOffset = padding,
tabPositions = tabPositions,
selectedTab = selectedTabIndex
)
}
}
}
}
If you copy-paste source code and change minimumTabWidth to 0 you will be able to assign any width modifier
/**
* Material Design scrollable tabs.
*
* When a set of tabs cannot fit on screen, use scrollable tabs. Scrollable tabs can use longer text
* labels and a larger number of tabs. They are best used for browsing on touch interfaces.
*
* ![Scrollable tabs image](https://developer.android.com/images/reference/androidx/compose/material/scrollable-tabs.png)
*
* A ScrollableTabRow contains a row of [Tab]s, and displays an indicator underneath the currently
* selected tab. A ScrollableTabRow places its tabs offset from the starting edge, and allows
* scrolling to tabs that are placed off screen. For a fixed tab row that does not allow
* scrolling, and evenly places its tabs, see [TabRow].
*
* #param selectedTabIndex the index of the currently selected tab
* #param modifier optional [Modifier] for this ScrollableTabRow
* #param backgroundColor The background color for the ScrollableTabRow. Use [Color.Transparent] to
* have no color.
* #param contentColor The preferred content color provided by this ScrollableTabRow to its
* children. Defaults to either the matching content color for [backgroundColor], or if
* [backgroundColor] is not a color from the theme, this will keep the same value set above this
* ScrollableTabRow.
* #param edgePadding the padding between the starting and ending edge of ScrollableTabRow, and
* the tabs inside the ScrollableTabRow. This padding helps inform the user that this tab row can
* be scrolled, unlike a [TabRow].
* #param indicator the indicator that represents which tab is currently selected. By default this
* will be a [TabRowDefaults.Indicator], using a [TabRowDefaults.tabIndicatorOffset]
* modifier to animate its position. Note that this indicator will be forced to fill up the
* entire ScrollableTabRow, so you should use [TabRowDefaults.tabIndicatorOffset] or similar to
* animate the actual drawn indicator inside this space, and provide an offset from the start.
* #param divider the divider displayed at the bottom of the ScrollableTabRow. This provides a layer
* of separation between the ScrollableTabRow and the content displayed underneath.
* #param tabs the tabs inside this ScrollableTabRow. Typically this will be multiple [Tab]s. Each
* element inside this lambda will be measured and placed evenly across the TabRow, each taking
* up equal space.
*/
#Composable
#UiComposable
fun MyScrollableTabRow(
selectedTabIndex: Int,
modifier: Modifier = Modifier,
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
edgePadding: Dp = TabRowDefaults.ScrollableTabRowPadding,
indicator: #Composable #UiComposable
(tabPositions: List<TabPosition>) -> Unit = #Composable { tabPositions ->
TabRowDefaults.Indicator(
Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex])
)
},
divider: #Composable #UiComposable () -> Unit =
#Composable {
TabRowDefaults.Divider()
},
tabs: #Composable #UiComposable () -> Unit
) {
Surface(
modifier = modifier,
color = backgroundColor,
contentColor = contentColor
) {
val scrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val scrollableTabData = remember(scrollState, coroutineScope) {
ScrollableTabData(
scrollState = scrollState,
coroutineScope = coroutineScope
)
}
SubcomposeLayout(
Modifier.fillMaxWidth()
.wrapContentSize(align = Alignment.CenterStart)
.horizontalScroll(scrollState)
.selectableGroup()
.clipToBounds()
) { constraints ->
val minTabWidth = ScrollableTabRowMinimumTabWidth.roundToPx()
val padding = edgePadding.roundToPx()
val tabConstraints = constraints.copy(minWidth = 0)
val tabPlaceables = subcompose(TabSlots.Tabs, tabs)
.map { it.measure(tabConstraints) }
var layoutWidth = padding * 2
var layoutHeight = 0
tabPlaceables.forEach {
layoutWidth += it.width
layoutHeight = maxOf(layoutHeight, it.height)
}
// Position the children.
layout(layoutWidth, layoutHeight) {
// Place the tabs
val tabPositions = mutableListOf<TabPosition>()
var left = padding
tabPlaceables.forEach {
it.placeRelative(left, 0)
tabPositions.add(TabPosition(left = left.toDp(), width = it.width.toDp()))
left += it.width
}
// The divider is measured with its own height, and width equal to the total width
// of the tab row, and then placed on top of the tabs.
subcompose(TabSlots.Divider, divider).forEach {
val placeable = it.measure(
constraints.copy(
minHeight = 0,
minWidth = layoutWidth,
maxWidth = layoutWidth
)
)
placeable.placeRelative(0, layoutHeight - placeable.height)
}
// The indicator container is measured to fill the entire space occupied by the tab
// row, and then placed on top of the divider.
subcompose(TabSlots.Indicator) {
indicator(tabPositions)
}.forEach {
it.measure(Constraints.fixed(layoutWidth, layoutHeight)).placeRelative(0, 0)
}
scrollableTabData.onLaidOut(
density = this#SubcomposeLayout,
edgeOffset = padding,
tabPositions = tabPositions,
selectedTab = selectedTabIndex
)
}
}
}
}
/**
* Data class that contains information about a tab's position on screen, used for calculating
* where to place the indicator that shows which tab is selected.
*
* #property left the left edge's x position from the start of the [TabRow]
* #property right the right edge's x position from the start of the [TabRow]
* #property width the width of this tab
*/
#Immutable
class TabPosition internal constructor(val left: Dp, val width: Dp) {
val right: Dp get() = left + width
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TabPosition) return false
if (left != other.left) return false
if (width != other.width) return false
return true
}
override fun hashCode(): Int {
var result = left.hashCode()
result = 31 * result + width.hashCode()
return result
}
override fun toString(): String {
return "TabPosition(left=$left, right=$right, width=$width)"
}
}
/**
* Contains default implementations and values used for TabRow.
*/
object TabRowDefaults {
/**
* Default [Divider], which will be positioned at the bottom of the [TabRow], underneath the
* indicator.
*
* #param modifier modifier for the divider's layout
* #param thickness thickness of the divider
* #param color color of the divider
*/
#Composable
fun Divider(
modifier: Modifier = Modifier,
thickness: Dp = DividerThickness,
color: Color = LocalContentColor.current.copy(alpha = DividerOpacity)
) {
androidx.compose.material.Divider(modifier = modifier, thickness = thickness, color = color)
}
/**
* Default indicator, which will be positioned at the bottom of the [TabRow], on top of the
* divider.
*
* #param modifier modifier for the indicator's layout
* #param height height of the indicator
* #param color color of the indicator
*/
#Composable
fun Indicator(
modifier: Modifier = Modifier,
height: Dp = IndicatorHeight,
color: Color = LocalContentColor.current
) {
Box(
modifier
.fillMaxWidth()
.height(height)
.background(color = color)
)
}
/**
* [Modifier] that takes up all the available width inside the [TabRow], and then animates
* the offset of the indicator it is applied to, depending on the [currentTabPosition].
*
* #param currentTabPosition [TabPosition] of the currently selected tab. This is used to
* calculate the offset of the indicator this modifier is applied to, as well as its width.
*/
fun Modifier.tabIndicatorOffset(
currentTabPosition: TabPosition
): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "tabIndicatorOffset"
value = currentTabPosition
}
) {
val currentTabWidth by animateDpAsState(
targetValue = currentTabPosition.width,
animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
)
val indicatorOffset by animateDpAsState(
targetValue = currentTabPosition.left,
animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
)
fillMaxWidth()
.wrapContentSize(Alignment.BottomStart)
.offset(x = indicatorOffset)
.width(currentTabWidth)
}
/**
* Default opacity for the color of [Divider]
*/
const val DividerOpacity = 0.12f
/**
* Default thickness for [Divider]
*/
val DividerThickness = 1.dp
/**
* Default height for [Indicator]
*/
val IndicatorHeight = 2.dp
/**
* The default padding from the starting edge before a tab in a [ScrollableTabRow].
*/
val ScrollableTabRowPadding = 52.dp
}
private enum class TabSlots {
Tabs,
Divider,
Indicator
}
/**
* Class holding onto state needed for [ScrollableTabRow]
*/
private class ScrollableTabData(
private val scrollState: ScrollState,
private val coroutineScope: CoroutineScope
) {
private var selectedTab: Int? = null
fun onLaidOut(
density: Density,
edgeOffset: Int,
tabPositions: List<TabPosition>,
selectedTab: Int
) {
// Animate if the new tab is different from the old tab, or this is called for the first
// time (i.e selectedTab is `null`).
if (this.selectedTab != selectedTab) {
this.selectedTab = selectedTab
tabPositions.getOrNull(selectedTab)?.let {
// Scrolls to the tab with [tabPosition], trying to place it in the center of the
// screen or as close to the center as possible.
val calculatedOffset = it.calculateTabOffset(density, edgeOffset, tabPositions)
if (scrollState.value != calculatedOffset) {
coroutineScope.launch {
scrollState.animateScrollTo(
calculatedOffset,
animationSpec = ScrollableTabRowScrollSpec
)
}
}
}
}
}
/**
* #return the offset required to horizontally center the tab inside this TabRow.
* If the tab is at the start / end, and there is not enough space to fully centre the tab, this
* will just clamp to the min / max position given the max width.
*/
private fun TabPosition.calculateTabOffset(
density: Density,
edgeOffset: Int,
tabPositions: List<TabPosition>
): Int = with(density) {
val totalTabRowWidth = tabPositions.last().right.roundToPx() + edgeOffset
val visibleWidth = totalTabRowWidth - scrollState.maxValue
val tabOffset = left.roundToPx()
val scrollerCenter = visibleWidth / 2
val tabWidth = width.roundToPx()
val centeredTabOffset = tabOffset - (scrollerCenter - tabWidth / 2)
// How much space we have to scroll. If the visible width is <= to the total width, then
// we have no space to scroll as everything is always visible.
val availableSpace = (totalTabRowWidth - visibleWidth).coerceAtLeast(0)
return centeredTabOffset.coerceIn(0, availableSpace)
}
}
private val ScrollableTabRowMinimumTabWidth = 90.dp
/**
* [AnimationSpec] used when scrolling to a tab that is not fully visible.
*/
private val ScrollableTabRowScrollSpec: AnimationSpec<Float> = tween(
durationMillis = 250,
easing = FastOutSlowInEasing
)

Jetpack Compose Textfield value not getting updated

I'm trying to create a display where users can input a duration composed of hours, minutes and seconds. I manage the state of the duration with a class i wrote called TimeData. I set the value for the textfield to the state values, however this does not get updated when it changes. I have tried alot and i can't seem to figure out why this does not work, as similar implementations work just fine.
I save the state in viewmodel, inject it into the screen (composable) the screen passes fields of the TimeData to the three composables for the hours, seconds and minutes. These components handle displaying the textfields and changing the values
I've tried changing state directly, saving state in screen file with by remember instead of in viewmodel with State, i've tried changing val to var and back in the TimeData object and it's children. And much more.
p.s. this is my first question here, so if anything is not clear, please let me know.
TimeData class (saved as state in viewmodel)
data class TimeData(
val hours: TimeUnit = TimeUnit(TimeUnits.HOURS),
val mins: TimeUnit = TimeUnit(TimeUnits.MINS),
val secs: TimeUnit = TimeUnit(TimeUnits.SECS),
) {
fun isDataEmpty() = hours.value == 0L && mins.value == 0L && secs.value == 0L
}
fun TimeData.toISOString(): String = "PT" +
"${hours.value}${hours.unit.firstLetter}" +
"${mins.value}${mins.unit.firstLetter}" +
"${secs.value}${secs.unit.firstLetter}"
fun TimeData.toDuration(): Duration = Duration.parse(this.toISOString())
TimeUnit class (this value is updated)
data class TimeUnit(
var unit: TimeUnits
) {
var value: Long = 0
set(value) {
val parsedValue = value
val min = 0
val max = when (unit) {
TimeUnits.HOURS -> 99
TimeUnits.MINS -> 60
TimeUnits.SECS -> 60
}
if (parsedValue in min..max) {
field = value
}
}
override fun toString(): String {
return if (value in 1..9) "0$value" else value.toString()
}
}
enum class TimeUnits(val firstLetter: String) {
HOURS("h"),
MINS("m"),
SECS("s")
}
State in viewmodel
private val _timeState = mutableStateOf(TimeData())
val timeState: State<TimeData> = _timeState
Texfield
BasicTextField(
modifier = Modifier.widthIn(1.dp),
value = time.value.toString(),
onValueChange = {
if (it.isNotBlank()) {
//changing state directly
time.value = it.toLong()
//letting viewmodel handel change
viewModel.onEvent(AddEditExerciseEvents.DurationValueChanged(time))
}
},
singleLine = true,
textStyle = TextStyle(
fontSize = 32.sp,
fontWeight = FontWeight.Medium,
color = textColor,
textAlign = TextAlign.Center
),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
Changing state value in viewmodel
when (event) {
is AddEditExerciseEvents.DurationValueChanged -> {
when (event.value.unit) {
TimeUnits.HOURS -> {
_timeState.value = timeState.value.copy(
hours = event.value
)
}
TimeUnits.MINS -> {
_timeState.value = timeState.value.copy(
mins = event.value
)
}
TimeUnits.SECS -> {
_timeState.value = timeState.value.copy(
secs = event.value
)
}
}
}

Continuous recomposition in Jetpack Compose

I'm trying to create a sky view in my Android app using Jetpack Compose. I want to display it inside a Card with a fixed height. During nigth time, the card background turns dark blue and I'd like to have some blinking stars spread over the sky.
To create the stars blinking animation, I'm using an InfiniteTransition object and a scale property with animateFloat that I apply to several Icons. Those Icons are created inside a BoxWithConstraints, to spread then randomly using a for loop. The full code I'm using is shown below:
#Composable
fun NightSkyCard() {
Card(
modifier = Modifier
.height(200.dp)
.fillMaxWidth(),
elevation = 2.dp,
shape = RoundedCornerShape(20.dp),
backgroundColor = DarkBlue
) {
val infiniteTransition = rememberInfiniteTransition()
val scale by infiniteTransition.animateFloat(
initialValue = 1f,
targetValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
)
)
BoxWithConstraints(
modifier = Modifier.fillMaxSize()
) {
for (n in 0..20) {
val size = Random.nextInt(3, 5)
val start = Random.nextInt(0, maxWidth.value.toInt())
val top = Random.nextInt(10, maxHeight.value.toInt())
Icon(
imageVector = Icons.Filled.Circle,
contentDescription = null,
modifier = Modifier
.padding(start = start.dp, top = top.dp)
.size(size.dp)
.scale(scale),
tint = Color.White
)
}
}
}
}
The problem with this code is that the BoxWithConstraints's scope is recomposing continously, so I get a lot of dots appearing and dissapearing from the screen very fast. I'd like the scope to just run once, so that the dots created at first time would blink using the scale property animation. How could I achieve that?
Instead of continuous recomposition you should look for least amount of recompositions to achieve your goal.
Compose has 3 phases. Composition, Layout and Draw, explained in official document. When you use a lambda you defer state read from composition to layout or draw phase.
If you use Modifier.scale() or Modifier.offset() both of three phases above are called. If you use Modifier.graphicsLayer{scale} or Modifier.offset{} you defer state read to layout phase. And the best part, if you use Canvas, which is a Spacer with Modifier.drawBehind{} under the hood, you defer state read to draw phase as in example below and you achieve your goal only with 1 composition instead of recomposing on every frame.
For instance from official document
// Here, assume animateColorBetween() is a function that swaps between
// two colors
val color by animateColorBetween(Color.Cyan, Color.Magenta)
Box(Modifier.fillMaxSize().background(color))
Here the box's background color is switching rapidly between two
colors. This state is thus changing very frequently. The composable
then reads this state in the background modifier. As a result, the box
has to recompose on every frame, since the color is changing on every
frame.
To improve this, we can use a lambda-based modifier–in this case,
drawBehind. That means the color state is only read during the draw
phase. As a result, Compose can skip the composition and layout phases
entirely–when the color changes, Compose goes straight to the draw
phase.
val color by animateColorBetween(Color.Cyan, Color.Magenta)
Box(
Modifier
.fillMaxSize()
.drawBehind {
drawRect(color)
}
)
And how you can achieve your result
#Composable
fun NightSkyCard2() {
Card(
modifier = Modifier
.height(200.dp)
.fillMaxWidth(),
elevation = 2.dp,
shape = RoundedCornerShape(20.dp),
backgroundColor = Color.Blue
) {
val infiniteTransition = rememberInfiniteTransition()
val scale by infiniteTransition.animateFloat(
initialValue = 1f,
targetValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
)
)
val stars = remember { mutableStateListOf<Star>() }
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
.background(Color.Blue)
) {
SideEffect {
println("🔥 Recomposing")
}
LaunchedEffect(key1 = Unit) {
repeat(20) {
stars.add(
Star(
Random.nextInt(2, 5).toFloat(),
Random.nextInt(0, constraints.maxWidth).toFloat(),
Random.nextInt(10, constraints.maxHeight).toFloat()
)
)
}
}
Canvas(modifier = Modifier.fillMaxSize()) {
if(stars.size == 20){
stars.forEach { star ->
drawCircle(
Color.White,
center = Offset(star.xPos, star.yPos),
radius = star.radius *(scale)
)
}
}
}
}
}
}
#Immutable
data class Star(val radius: Float, val xPos: Float, val yPos: Float)
One solution is to wrap your code in a LaunchedEffect so that the animation runs once:
#Composable
fun NightSkyCard() {
Card(
modifier = Modifier
.height(200.dp)
.fillMaxWidth(),
elevation = 2.dp,
shape = RoundedCornerShape(20.dp),
backgroundColor = DarkBlue
) {
val infiniteTransition = rememberInfiniteTransition()
val scale by infiniteTransition.animateFloat(
initialValue = 1f,
targetValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
)
)
BoxWithConstraints(
modifier = Modifier.fillMaxSize()
) {
for (n in 0..20) {
var size by remember { mutableStateOf(0) }
var start by remember { mutableStateOf(0) }
var top by remember { mutableStateOf(0) }
LaunchedEffect(key1 = Unit) {
size = Random.nextInt(3, 5)
start = Random.nextInt(0, maxWidth.value.toInt())
top = Random.nextInt(10, maxHeight.value.toInt())
}
Icon(
imageVector = Icons.Filled.Circle,
contentDescription = null,
modifier = Modifier
.padding(start = start.dp, top = top.dp)
.size(size.dp)
.scale(scale),
tint = Color.White
)
}
}
}
}
You then get 21 blinking stars.

Can I change the value of a component from a separate button in Compose Multiplatform?

I am trying to make a desktop application that allows you to search through a number of predefined locations stored in Kotlin classes in a separate directory. To accomplish this, I've used the reflections and compose-jb libraries.
The problem I've run into is that I can't figure out how to update a Column of Boxes (located in another Box component) to change when I press the search button after entering tags that I want to search by.
My code is below (for the Main.kt file) that describes the entire desktop application.
val reflections = Reflections("io.github.mobomega.project.attractions")
var display = mutableSetOf<Attraction>()
fun main() = application {
val stateVertical = rememberScrollState(0)
val stateHorizontal = rememberScrollState(0)
var state = Box(
modifier = Modifier
.fillMaxSize()
.verticalScroll(stateVertical)
.padding(end = 12.dp, bottom = 12.dp)
.horizontalScroll(stateHorizontal)
)
Window(
onCloseRequest = ::exitApplication,
title = "Search",
state = rememberWindowState(width = 2256.dp, height = 1504.dp)
) {
val count = remember { mutableStateOf(1) }
MaterialTheme {
Column {
val text = remember { mutableStateOf("") }
OutlinedTextField(
value = text.value,
singleLine = true,
onValueChange = { text.value = it },
modifier = Modifier.align(Alignment.CenterHorizontally)
)
Row (modifier = Modifier.size(2256.dp, 50.dp), horizontalArrangement = Arrangement.Center) {
Button(modifier = Modifier.align(Alignment.Top),
onClick = {
val tags = text.value.split(", ", ",")
for (tag in tags) {
search(tag.lowercase())
println("$display have tag $tag")
}
// Setting the new value of the Box
state = create(stateVertical, stateHorizontal)
// Creates error:
// "#Composable invocations can only happen from the context of a #Composable function"
}) {
Text("Search")
}
Button (modifier = Modifier.align(Alignment.Top),
onClick = {
display.clear()
}) {
Text("Reset")
}
}
Row (horizontalArrangement = Arrangement.Center) {
Box(
modifier = Modifier.fillMaxSize()
.background(color = Color(red = 0xFF, green = 0xFF, blue = 0xFF))
.padding(10.dp)
) {
state // Creating the state Box component in the Row
VerticalScrollbar(
modifier = Modifier.align(Alignment.CenterEnd)
.fillMaxHeight(),
adapter = rememberScrollbarAdapter(stateVertical)
)
HorizontalScrollbar(
modifier = Modifier.align(Alignment.BottomStart)
.fillMaxWidth()
.padding(end = 12.dp),
adapter = rememberScrollbarAdapter(stateHorizontal)
)
}
}
}
}
}
}
#Composable
fun textBox(text: String = "Item") {
Box(
modifier = Modifier.height(32.dp)
.width(400.dp)
.background(color = Color(200, 0, 0, 20))
.padding(start = 10.dp),
contentAlignment = Alignment.CenterStart
) {
Text(text = text)
}
}
#Composable
fun create(stateVertical: ScrollState, stateHorizontal: ScrollState) = Box(
modifier = Modifier
.fillMaxSize()
.verticalScroll(stateVertical)
.padding(end = 12.dp, bottom = 12.dp)
.horizontalScroll(stateHorizontal)
) {
Column {
var x = 0
for (attr in display) {
x++
textBox(attr.name)
if (x < display.size) {
Spacer(modifier = Modifier.height(5.dp).align(Alignment.CenterHorizontally))
}
}
}
}
fun search(text: String) {
for (attr in reflections.getSubTypesOf(Attraction::class.java)) {
val temp = attr.getConstructor().newInstance()
println("${temp.name} has tags ${temp.tags}")
if (temp.matches(text) && (temp !in display)) {
display += temp
}
}
}
I have tried to update the value of the Box that contains all of the items that match any of the search criteria, but I have run into a number of issues, such as the "onClick" function in which I set the new value of the "state" variable (storing all of the matching items) not being a Composable function, and therefore I can't change the value.
How would I accomplish changing the value of a Component such as a Box from another Component, such as a Button?
In Compose you can't create a view like you're doing with state variable. Result of your call is just Unit, and when you later call it you should see a warning "The expression is unused". The view is added at the tree hierarchy at the moment your variable is created.
To solve your problem you need to declare display as a mutable state - it's a new thing made especially for Compose, which allows triggering recomposition when this state changes:
val display by mutableStateOf<Attraction>(setOf())
And then update like this in your search:
val mutableDisplay = mutableSetOf<Attraction>()
// for
// ...
mutableDisplay += temp
// ...
display = mutableDisplay
Note that you can't use mutable set inside your mutable state, as mutable state won't be able to track changes of this set.
To learn more about state in Compose I suggest you checking this youtube video which explains the basic principles, and Compose mental model for better understanding of how to work with it.

How to get the rgb value on the screen

I have here my code which just displays a simple color palette:
#Composable
fun ColorPicker(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.fillMaxSize()
.background(Brush.horizontalGradient(colors()))
) {
}
}
fun colors(n: Int = 359): List<Color> {
val cols = mutableListOf<Color>()
for (i in 0 until n) {
val color = java.awt.Color.getHSBColor(i.toFloat() / n.toFloat(), 0.85f, 1.0f)
cols.add(Color(color.red, color.green, color.blue, color.alpha))
}
return cols
}
That looks pretty good:
But now I want to get the RGB Value if the usere clicks on the color palette. How would I do this? (This is Jetpack Compose Desktop but it should be the same as on Android)
You could instead create Cards of a very small width for each colour and modify a state holder from their onClicks
For example,
var rgb by mutableStateOf ("") // displays RGB values
Text(rgb)
Layout( content = {
for (i in 0 until 359) {
val color =
java.awt.Color.getHSBColor(i.toFloat() / n.toFloat(), 0.85f, 1.0f)
Card(
Modifier.background(Color(
color.red,
color.green,
color.blue,
color.alpha
)
),
onClick = { rgb = color. // Assign appropriate value
}
}
){measurables, constraints ->
val placeables = measurables.map{
it.measure(constraints.maxWidth/measurables.size, constraints.maxHeight)
}
int x = 0
layout(constraints.maxWidth, constraints.maxHeight){
placeables.forEach{
it.placeRelative(x, 0)
x+=it.width
}
}
}
This distributes width equally