ColorPickerWithTitle: Saving initialValue in rememberSaveable(prevents unwanted reset). (v1.0.1)

This commit is contained in:
acclorite 2024-06-13 20:15:37 +03:00
parent 09f9bbc027
commit 3f3e285b60

View file

@ -16,6 +16,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@ -29,6 +30,13 @@ import ua.acclorite.book_story.presentation.components.CustomIconButton
/** /**
* Color picker with title. * Color picker with title.
*
* @param modifier Modifier.
* @param value Target [Color].
* @param title Title.
* @param horizontalPadding Horizontal item padding.
* @param verticalPadding Vertical item padding.
* @param onValueChange Callback when target color changes.
*/ */
@Composable @Composable
fun ColorPickerWithTitle( fun ColorPickerWithTitle(
@ -39,7 +47,7 @@ fun ColorPickerWithTitle(
verticalPadding: Dp = 8.dp, verticalPadding: Dp = 8.dp,
onValueChange: (Color) -> Unit onValueChange: (Color) -> Unit
) { ) {
val initialValue = remember { value } val initialValue = rememberSaveable { value.value.toString() }
var color by remember { mutableStateOf(value) } var color by remember { mutableStateOf(value) }
Column( Column(
@ -54,7 +62,7 @@ fun ColorPickerWithTitle(
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp))
RevertibleSlider( RevertibleSlider(
value = color.red to "", value = color.red to "",
initialValue = initialValue.red, initialValue = Color(initialValue.toULong()).red,
title = stringResource(id = R.string.red_color), title = stringResource(id = R.string.red_color),
onValueChange = { onValueChange = {
color = color.copy(red = it) color = color.copy(red = it)
@ -63,7 +71,7 @@ fun ColorPickerWithTitle(
) )
RevertibleSlider( RevertibleSlider(
value = color.green to "", value = color.green to "",
initialValue = initialValue.green, initialValue = Color(initialValue.toULong()).green,
title = stringResource(id = R.string.green_color), title = stringResource(id = R.string.green_color),
onValueChange = { onValueChange = {
color = color.copy(green = it) color = color.copy(green = it)
@ -72,7 +80,7 @@ fun ColorPickerWithTitle(
) )
RevertibleSlider( RevertibleSlider(
value = color.blue to "", value = color.blue to "",
initialValue = initialValue.blue, initialValue = Color(initialValue.toULong()).blue,
title = stringResource(id = R.string.blue_color), title = stringResource(id = R.string.blue_color),
onValueChange = { onValueChange = {
color = color.copy(blue = it) color = color.copy(blue = it)