Jetpack compose - Lazy Column crashes on Recompose - android

Hi I am using Jetpack Compose to create a Heterogenous list. I was successful in implementing it. My requirement is when I try to click an Item in the list, I need to recompose the list. The app crashes when tried to refresh the list with below exception:
java.lang.IllegalStateException: Vertically scrollable component was measured with an infinity maximum height constraints, which is disallowed. One of the common reasons is nesting layouts like LazyColumn and Column(Modifier.verticalScroll()). If you want to add a header before the list of items please add a header as a separate item() before the main items() inside the LazyColumn scope. There are could be other reasons for this to happen: your ComposeView was added into a LinearLayout with some weight, you applied Modifier.wrapContentSize(unbounded = true) or wrote a custom layout. Please try to remove the source of infinite constraints in the hierarchy above the scrolling container
My code is below:
#Composable fun PrepareOverViewScreen(overViewList: List<OverViewListItem>) {
Scaffold(topBar = { TopBar("OverView") },
content = { DisplayOverViewScreen(overViewList = overViewList) },
backgroundColor = Color(0xFFf2f2f2)
)
}
#Composable fun DisplayOverViewScreen(
modifier: Modifier = Modifier, overViewList: List<OverViewListItem>
) {
LazyColumn(modifier = modifier) {
items(overViewList) { data ->
when (data) {
is OverViewHeaderItem -> {
HeaderItem(data,overViewList)
}
}
}
}
}
HeaderItem Composable Function is below :
#Composable fun HeaderItem(overViewHeaderItem: OverViewHeaderItem,overViewList: List<OverViewListItem>) { <br>
var angle by remember {
mutableStateOf(0f)
}
var canDisplayChild by remember {
mutableStateOf(false)
}
**if(canDisplayChild){
HandleHistoryTodayChild(canDisplayChild = true,overViewList)
}**
when (overViewHeaderItem.listType) {
ItemType.IN_PROGRESS_HEADER -> {
Column(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.background(color = Color(0xffdc8633)),
verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.Start
) {
Text(
text = "In Progress", color = Color.White,
modifier = Modifier.padding(start = 16.dp)
)
}
}
ItemType.HISTORY_TODAY_HEADER -> {
Column(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.background(color = Color(0xffd7d7d7)),
verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.Start
) {
Text(
text = stringResource(R.string.history_label), color = Color.Black,
modifier = Modifier.padding(start = 16.dp)
)
}
}
else -> {
Row(modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.background(color = Color(0xffd7d7d7)),
horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(R.string.history_yesterday), color = Color.Black,
modifier = Modifier.padding(start = 16.dp)
)
Spacer(Modifier.weight(1f))
**Image(
painter = painterResource(id = R.drawable.ic_expand_more),
modifier = Modifier
.padding(end = 5.dp)
.rotate(angle)
.clickable {
angle = (angle + 180) % 360f
canDisplayChild = !canDisplayChild
},
contentDescription = "Expandable Image"
)**
}
}
}
}
Handle History info where recomposition is called
#Composable
fun HandleHistoryTodayChild(canDisplayChild:Boolean,overViewList: List<OverViewListItem>) {
if(canDisplayChild){
**PrepareOverViewScreen(overViewList = overViewList)**
}
}

Your problem should be:
Spacer(Modifier.weight(1f))
Try to specify a fixed height and work your solution from there.

Related

Manage visibility with Compose UI

i´m new in Compose and i´m trying to manage the visibility of the TopBar when i´m scrolling a list ( LazyColumn ). I´m not pretend to use the Scaffold with Material 3 because I want to learn a bit more about Compose and Animation.
So, first of all, this is my code and it works just fine ->
#Composable
fun FavouriteCompose(stateUi: FavouriteStateUi.ShowMovies) {
Box(Modifier.fillMaxSize()) {
val state = rememberLazyListState()
val firstVisible = remember { derivedStateOf { state.firstVisibleItemIndex } }
Column(
Modifier
.fillMaxSize()
.background(color = GreenB)
) {
AnimatedVisibility(visible = firstVisible.value == 0) {
Spacer(modifier = Modifier.height(20.dp))
Paragraphs.Paragraph(
modifier = Modifier.padding(10.dp),
stringRes = R.string.favourite,
color = Color.White,
paragraphSize = Paragraphs.ParagraphSize.PARAGRAPH_24_SP
)
Spacer(modifier = Modifier.height(20.dp))
}
if (stateUi.movies?.isEmpty() == true) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(top = 10.dp)
.fillMaxSize()
.clip(RoundedCornerShape(10.dp))
.background(Color.White),
) {
Image(
alignment = Alignment.Center,
modifier = Modifier.size(200.dp),
painter = painterResource(
id = R.drawable.ic_baseline_local_movies_24
),
contentDescription = ""
)
Paragraphs.Paragraph(
modifier = Modifier
.padding(top = 10.dp)
.align(Alignment.CenterHorizontally),
stringRes = R.string.add_more_movies,
paragraphSize = Paragraphs.ParagraphSize.PARAGRAPH_24_SP
)
}
} else {
LazyColumn(
state = state,
modifier = Modifier
.fillMaxSize()
.clip(RoundedCornerShape(10.dp))
.background(Color.White)
.padding(10.dp)
) {
items(
items = stateUi.movies.orEmpty(),
key = { cardModel -> cardModel.id }
) { item -> MovieCard(item) }
}
}
}
val snackBarModel = stateUi.snackBarModel
if (snackBarModel.addOrRemoveMovie == true) {
Box(
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(bottom = 10.dp)
) {
SnackBar(
stringRes = R.string.pelicula_removida,
icon = R.drawable.ic_baseline_local_movies_24,
backgroundColor = Color.Black,
textColor = LightGrey,
iconColor = Blue,
snackBarModel = snackBarModel
)
}
}
}
}
Each Time i swipe the list the topApp hides and viceversa, but i´m not sure if this is the best way to do this ( without using Scaffold with Material 3 ).
I´m creating more recompositons with this kind of solution ?, should I save the lazy state in a viewModel instead?
Thanks!.

Top app bar not scrolling when custom size is set

Whenever I navigate within my screen the LazyColumn scrolls perfectly but the top app bar doesn't move at all. Is it possible to tell the enlarged top app bar to scroll or can this only be done with the 4 default top app bars provided in Material 3?
#Composable
fun MyScreen(navController: NavController) {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
val mConfiguration = LocalConfiguration.current
val mScreenHeight = mConfiguration.screenHeightDp.dp
val mSize = mScreenHeight / 2
Column {
Box(
modifier = Modifier
.height(mSize)
.weight(1f)
.fillMaxWidth()
) {
LargeTopAppBar(
title = {
Text(
text = "Android Studio Dolphin", overflow = TextOverflow.Visible, maxLines = 1
)
},
scrollBehavior = scrollBehavior)
}
Box(
modifier = Modifier
.height(mSize)
.weight(1f)
.fillMaxWidth()
.background(Color.Green)
) {
MyScreenContent()
// contentPadding ->
// MyScreenContent(contentPadding = contentPadding)
}
}
}
#Composable
fun MyScreenContent(
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues()
) {
Box(modifier = modifier.fillMaxSize()) {
val listState = rememberLazyListState()
LazyColumn(
state = listState,
contentPadding = contentPadding,
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp)
) {
item {
Text(text = "text", style = TextStyle(fontSize = 18.sp))
}
items(75) {
ListItem(it)
}
}
}
}
You should use a Scaffold applying the nestedScroll modifier.
Something like:
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
LargeTopAppBar(
title = {
Text(
text = "Android Studio Dolphin", overflow = TextOverflow.Visible, maxLines = 1
)
},
scrollBehavior = scrollBehavior)
},
content = { innerPadding ->
LazyColumn(contentPadding = innerPadding,){
//....
}
}
)

Android Compose, clickable surface on top of buttons

Is it possible to create full screen, clickable, transparent surface/box, that will overlap compose buttons and other composables. I want to keep buttons visible but unreachable for the user.
When I set them(buttons) as disabled, they turn to an unclickable area( on top of the clickable surface) that I can't have on the screen. Other composables, like Text,Box etc. act like they are "under" clickable surface.
#Composable
fun ShowAnswers(question: Question, onSurfaceClick: () -> Unit, questionsLeft: Int) {
Surface(modifier = Modifier.clickable { onSurfaceClick() }) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(8.dp)
) {
Text(
text = stringResource(id = R.string.questions_left, questionsLeft),
fontSize = 24.sp
)
Spacer(modifier = Modifier.height(20.dp))
QuestionCard(question = question)
Spacer(modifier = Modifier.height(20.dp))
ShowCorrectAnswer(question = question)
}
}
}
ShowCorrectAnswer(...) contains buttons that i need to "overlap"
You can use a simple transparent Box to overlay the Surface with the question.
Something like:
var isActive by remember { mutableStateOf(false) }
Box(modifier = Modifier.fillMaxSize()) {
Surface() {
Column() {
//....
QuestionCard(question = question)
//....
Button(onClick = { isActive = true }) {
//...
}
}
}
if (isActive){
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Transparent)
.clickable(
enabled=isActive,
interactionSource = interactionSource,
indication = null)
{
//do something
}
)
}
}
Adding a fillMaxSize Box inside the surface, after column, solved the problem.
But placing the Box before Column makie it appear "under" it.
#Composable
fun ShowAnswers(question: Question, onSurfaceClick: () -> Unit, questionsLeft: Int) {
Surface {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(8.dp)
) {
Text(
text = stringResource(id = R.string.questions_left, questionsLeft),
fontSize = 24.sp
)
Spacer(modifier = Modifier.height(20.dp))
QuestionCard(question = question)
Spacer(modifier = Modifier.height(20.dp))
ShowCorrectAnswer(question = question)
}
**Box(modifier = Modifier
.fillMaxSize()
.background(Color.Transparent)
.clickable { onSurfaceClick() })**
}
}

How to optimise laggy JetPack Compose layout

I'm using a HorizontalPager from accompanist package. The pager will have 1 page for each exercise stored by the user.
Each page in the pager has a LazyColumn which contain multiple cards with controls such as IconButtons and BasicTextField. The number of cards depends on number of sets configured by the user. I expect the typical number to be between 1 to 8 but only 3 to 5 would be visible on the screen at any given time (depending on the screen size and resolution).
The issue is that when this layout produces noticeable lag (animations skip frames) every time the HorizontalPager needs to build a new page that has more than 3 cards. This happens when swapping between pages. The same happens in debug and release versions running on a real device (Galaxy S10e) and emulator.
I'm trying to optimise this layout, so each frame renders in no more than 16ms regardless of the number of cards shown on the screen.
I've previously tried to solve this issue by setting fixed heights to some composables but that didn't help much. I've also tried using Text instead of BasicTextField, which would be then replaced with BasicTextField when users taps on the text but this hasn't helped much, therefore I removed this implementation.
Do you have some suggestions how performance of this layout could be improved to eliminate the lag?
Below is my code, screen shoot of the app screen and profiler:
#ExperimentalPagerApi
#Composable
fun WorkoutSessionScreen(
navHostController: NavHostController,
) {
val pagerState = rememberPagerState()
Scaffold(
topBar = { MyTopAppBar(navHostController = navHostController) }
) {
Box(
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
.background(MaterialTheme.colors.background)
.imePadding()
) {
HorizontalPager(
count = 10, state =
pagerState,
itemSpacing = 16.dp
) {
Log.e("==>", "Building horizontal pager")
TrackingControls()
}
Box(
modifier = Modifier
.height(70.dp)
.fillMaxWidth()
.background(Color(0xFAF7F7FF))
.align(Alignment.BottomCenter)
) {
Column(
Modifier.fillMaxWidth()
) {
Divider(color = Color(0x2A5C5C5C))
BottomControls()
}
}
}
}
}
#Composable
private fun TrackingControls() {
LazyColumn(
Modifier
.fillMaxHeight()
.fillMaxWidth(),
contentPadding = PaddingValues(vertical = 8.dp)
) {
items(6) { item ->
SetsAndRepsTrackingControls(
modifier = Modifier
)
}
}
}
#Composable
private fun BottomControls() {
Text(text = "Bottom Controlls")
}
#Composable
fun SetsAndRepsTrackingControls(modifier: Modifier = Modifier) {
val add = painterResource(id = R.drawable.ic_round_add_24)
val remove = painterResource(id = R.drawable.ic_round_remove_24)
Card(
modifier
.fillMaxWidth()
.height(200.dp)
.padding(vertical = 16.dp, horizontal = 8.dp),
backgroundColor = MaterialTheme.colors.surface,
shape = RoundedCornerShape(12.dp),
) {
Column() {
ControlsHeader()
TrackingInput(label = "REPS", add, remove)
Divider(color = Color.LightGray)
TrackingInput(label = "WEIGHT (KG)", add, remove)
}
}
}
#Composable
private fun ControlsHeader() {
Row(
modifier = Modifier
.height(56.dp)
.fillMaxWidth()
.background(MaterialTheme.colors.primary, RoundedCornerShape(12.dp))
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = "Set 1")
Text(text = "CheckBox")
}
}
#Composable
private fun TrackingInput(label: String = "Preview", add: Painter, remove: Painter) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(60.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = {}) {
Icon(
painter = painterResource(id = R.drawable.ic_round_remove_24),
contentDescription = "Minus",
tint = MaterialTheme.colors.onSurface
)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
BasicTextField(
singleLine = true,
value = "8",
onValueChange = {},
textStyle = TextStyle(
textAlign = TextAlign.Center,
color = MaterialTheme.colors.onSurface
),
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = label,
style = MaterialTheme.typography.overline.copy(color = MaterialTheme.colors.onSurface)
)
}
IconButton(onClick = { Log.d("==>", "tada") }) {
Icon(
painter = painterResource(id = R.drawable.ic_round_add_24),
contentDescription = "Minus",
tint = MaterialTheme.colors.onSurface
)
}
}
}
This profiler print screen shows rendering of a single card called SetsAndRepsTrackingControls

Kotlin jetpack compose deleting and adding elements to mutableStateListOf

I have wrote hardcoded list of ToDo elements and made 2 composable functions to display data.
#Composable
fun TodoAppContent() {
val todos = remember { (DataProvider.listOfToDoEntries) }
Column(
modifier = Modifier
.fillMaxSize()
.background(Color(0xff503d69))
) {
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
modifier = Modifier
.weight(1f)
) {
items(items = todos, itemContent = { CreateToDoListItem(todo = it) })
}
Button(
onClick = {},
modifier = Modifier
.size(60.dp)
.align(alignment = Alignment.CenterHorizontally),
colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xffc1b6d1)),
shape = CircleShape
) {
Text(text = "+")
}
}
}
#Composable
fun CreateToDoListItem(todo: ToDo) {
Card(
modifier = Modifier
.padding(horizontal = 8.dp, vertical = 8.dp)
.fillMaxWidth(),
elevation = 2.dp,
backgroundColor = Color(0xff694598),
shape = RoundedCornerShape(
topStart = 30.dp,
topEnd = 30.dp,
bottomStart = 0.dp,
bottomEnd = 30.dp
)
) {
Row {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.align(Alignment.CenterVertically)
) {
Text(text = todo.title, style = typography.h6)
Text(text = todo.description, style = typography.caption)
OutlinedButton(
onClick = {},
modifier = Modifier
.size(40.dp)
.align(alignment = Alignment.End),
colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xffc1b6d1)),
shape = CircleShape
) {
Text(text = "X")
}
}
}
}
}
It worked fine but when I wanted implement operations such as adding new entry to list and deleting it by changing
val todos = remember { mutableStateListOf(DataProvider.listOfToDoEntries) }
I'm no longer recieving single ToDo object but whole list. Any ideas how to recievie every single ToDo object of that mutableStateList?
Using mutableStateListOf you can create a mutable state list from some arguments.
So mutableStateListOf(DataProvider.listOfToDoEntries) will create a mutable list of lists, which is probably not what you want.
If you want to initialize a mutable state list with items from another list, you can use toMutableStateList:
val todos = remember { DataProvider.listOfToDoEntries.toMutableStateList() }

Categories

Resources