dynamically change text in cards - Jetpack Compose state - android

New to Compose and struggling hard with more complex state cases.
I cant seem to change the text dynamically in these cards, only set the text manually. Each button press should change the text in a box, starting left to right, leaving the next boxes empty.
What is wrong here?
UI:
val viewModel = HomeViewModel()
val guessArray = viewModel.guessArray
#Composable
fun HomeScreen() {
Column(
modifier = Modifier
.fillMaxWidth()
) {
WordGrid()
Keyboard()
}
}
#Composable
fun WordGrid() {
CardRow()
}
#Composable
fun Keyboard() {
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
MyKeyboardButton(text = "A", 35)
MyKeyboardButton(text = "B", 35)
}
}
#Composable
fun MyCard(text: String) {
Card(
modifier = Modifier
.padding(4.dp, 8.dp)
.height(55.dp)
.aspectRatio(1f),
backgroundColor = Color.White,
border = BorderStroke(2.dp, Color.Black),
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
text = text,
fontSize = 20.sp,
)
}
}
}
#Composable
fun CardRow() {
guessArray.forEach { rowCards ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
rowCards.forEach {
MyCard(it)
println(it)
}
}
}
}
#Composable
fun MyKeyboardButton(text: String, width: Int) {
Button(
onClick = {
guessArray[viewModel.currentRow][viewModel.column] = text
viewModel.column += 1
},
modifier = Modifier
.width(width.dp)
.height(60.dp)
.padding(0.dp, 2.dp)
) {
Text(text = text, textAlign = TextAlign.Center)
}
}
ViewModel:
class HomeViewModel : ViewModel() {
var currentRow = 0
var guessArray = Array(5) { Array(6) { "" }.toMutableList() }
var column = 0
}
The grid is created, but the text is never changed.

To make Compose view recompose with the new value, a mutable state should be used.
You're already using it with remember in your composable, but it also needs to be used in your view model for properties, which should trigger recomposition.
class HomeViewModel : ViewModel() {
var currentRow = 0
val guessArray = List(5) { List(6) { "" }.toMutableStateList() }
var column = 0
}

Related

New card item appearse only after phone rotation

I am writing a small gallery app for my cat. It has a button by clicking on which a new PhotoItem is added to the displayed list, but it appears only after phone rotation and I want it to appear on the screen right after button was clicked.
Right now everything is stored in a mutableList inside savedStateHandle.getStateFlow but I also tried regular MutableStateFlow and mutableStateOf and it didn't help. I havent really used jatpack compose and just can't figure what to do (
App
#SuppressLint("UnusedMaterialScaffoldPaddingParameter")
#Composable
fun BebrasPhotosApp() {
val galaryViewModel = viewModel<GalaryViewModel>()
val allPhotos by galaryViewModel.loadedPics.collectAsState()
Scaffold(topBar = { BebraTopAppBar() }, floatingActionButton = {
FloatingActionButton(
onClick = { galaryViewModel.addPicture() },
backgroundColor = MaterialTheme.colors.onBackground
) {
Icon(
imageVector = Icons.Rounded.Add,
contentDescription = "Add Photo",
tint = Color.White,
)
}
}) {
LazyColumn(modifier = Modifier.background(color = MaterialTheme.colors.background)) {
items(allPhotos) {
PhotoItem(bebra = it)
}
}
}
}
ViewModel
class GalaryViewModel(
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
val loadedPics = savedStateHandle.getStateFlow(
"pics", initialValue = mutableListOf<Bebra>(
Bebra(R.string.photo_1, R.string.desc_1, R.drawable.bebra_pic_1, R.string.add_desc_1),
Bebra(R.string.photo_2, R.string.desc_2, R.drawable.bebra_pic_2, R.string.add_desc_2),
Bebra(R.string.photo_3, R.string.desc_3, R.drawable.bebra_pic_3, R.string.add_desc_3)
)
)
fun addPicture() {
val additionalBebraPhoto = Bebra(
R.string.photo_placeholder,
R.string.desc_placeholder,
R.drawable.placeholder_cat,
R.string.add_desc_placeholder
)
savedStateHandle.get<MutableList<Bebra>>("pics")!!.add(additionalBebraPhoto)
}
}
PhotoItem
#Composable
fun PhotoItem(bebra: Bebra, modifier: Modifier = Modifier) {
var expanded by remember { mutableStateOf(false) }
Card(elevation = 4.dp, modifier = modifier
.padding(8.dp)
.clickable { expanded = !expanded }) {
Column(
modifier = modifier
.padding(8.dp)
.animateContentSize(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
) {
Text(
text = stringResource(id = bebra.PicNumber),
style = MaterialTheme.typography.h1,
modifier = modifier.padding(bottom = 8.dp)
)
Text(
text = stringResource(id = bebra.PicDesc),
style = MaterialTheme.typography.body1,
modifier = modifier.padding(bottom = 8.dp)
)
Image(
painter = painterResource(id = bebra.Picture),
contentDescription = stringResource(id = bebra.PicDesc),
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxWidth()
.height(256.dp)
.clip(RoundedCornerShape(12))
)
if (expanded) {
BebraAdditionalDesc(bebra.additionalDesc)
}
}
}
}
Bebra Data class
data class Bebra(
#StringRes val PicNumber: Int,
#StringRes val PicDesc: Int,
#DrawableRes val Picture: Int,
#StringRes val additionalDesc: Int
)
So, I am also not super familiar with JC, but from first glance it looks like your method, addPicture() - which is called when the user taps on the button, does not update the state, therefore there's no recomposition happening, so the UI does not get updated.
Check:
fun addPicture() {
// ...
savedStateHandle.get<MutableList<Bebra>>("pics")!!.add(additionalBebraPhoto)
}
So here you are basically adding a new item to savedStateHandle, which I assume does not trigger a recomposition.
What I think you need to do, is to update loadedPics, somehow.
However, loadedPics is a StateFlow, to be able to update it you would need a MutableStateFlow.
For simplicity, this is how you would do it if you were operating with a list of strings:
// declare MutableStateFlow that can be updated and trigger recomposition
val _loadedPics = MutableStateFlow(
savedStateHandle.get<MutableList<String>>("pics") ?: mutableListOf()
)
// use this in the JC layout to listen to state changes
val loadedPics: StateFlow<List<String>> = _loadedPics
// addPicture:
val prevList = _loadedPics.value
prevList.add("item")
_loadedPics.value = prevList // triggers recomposition
// here you probably will want to save the item in the
// `savedStateHandle` as you already doing.

Sorting List Items in LazyColumn - Android Jetpack Compose

Trying to implement a feature where the user is able to select a way to sort the list of Breweries when a certain item in a dropdown menu is selected (Name, City, Address). I am having trouble figuring out what I am doing wrong. Whenever I select example "Name" in the dropdown menu, the list of breweries does not sort. I am new at this so any advice will really help. Thank you!
Here is the full code for the MainScreen -
#SuppressLint("UnusedMaterialScaffoldPaddingParameter")
#RequiresApi(Build.VERSION_CODES.O)
#Composable
fun MainScreen(
navController: NavController,
mainViewModel: MainViewModel,
search: String?
) {
val apiData = brewData(mainViewModel = mainViewModel, search = search)
Scaffold(
content = {
if (apiData.loading == true){
Column(
modifier = Modifier
.fillMaxSize()
.background(colorResource(id = R.color.grey_blue)),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator()
}
} else if (apiData.data != null){
MainContent(bData = apiData.data!!, viewModel = mainViewModel)
}
},
topBar = { BrewTopBar(navController, search) }
)
}
#Composable
fun BrewTopBar(navController: NavController, search: String?) {
TopAppBar(
modifier = Modifier
.height(55.dp)
.fillMaxWidth(),
title = {
Text(
stringResource(id = R.string.main_title),
style = MaterialTheme.typography.h5,
maxLines = 1
)
},
actions = {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "$search")
IconButton(onClick = { navController.navigate(Screens.SearchScreen.name) }) {
Icon(
modifier = Modifier.padding(10.dp),
imageVector = Icons.Filled.Search,
contentDescription = stringResource(id = R.string.search)
)
}
}
},
backgroundColor = colorResource(id = R.color.light_purple)
)
}
#RequiresApi(Build.VERSION_CODES.O)
#Composable
fun MainContent(bData: List<BrewData>, viewModel: MainViewModel){
val allBreweries = bData.size
var sortByName by remember { mutableStateOf(false) }
var sortByCity by remember { mutableStateOf(false) }
var sortByAddress by remember { mutableStateOf(false) }
var dataSorted1 = remember { mutableStateOf(bData.sortedBy { it.name }) }
var dataSorted: MutableState<List<BrewData>>
Column(
modifier = Modifier
.fillMaxSize()
.background(colorResource(id = R.color.grey_blue))
){
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically
){
// Amount text label
Text(
text = "Result(s): ${bData.size}",
modifier = Modifier.padding(top = 15.dp, start = 15.dp, bottom = 5.dp)
)
SortingMenu(sortByName, sortByCity, sortByAddress) // needs mutable booleans for sorting
}
// List of Brewery cards
LazyColumn(
Modifier
.fillMaxSize()
.padding(5.dp)
){
items(allBreweries){ index ->
Breweries(
bData = when {
sortByName == true -> remember { mutableStateOf(bData.sortedBy { it.name }) }
sortByCity == true -> remember { mutableStateOf(bData.sortedBy { it.city }) }
sortByAddress == true -> remember { mutableStateOf(bData.sortedBy { it.address_2 }) }
else -> remember { mutableStateOf(bData) }
} as MutableState<List<BrewData>>, // Todo: create a way to select different sorting conditions
position = index,
viewModel = viewModel
)
}
}
}
}
#RequiresApi(Build.VERSION_CODES.O)
#Composable
fun Breweries(
bData: MutableState<List<BrewData>>,
position: Int,
viewModel: MainViewModel
){
val cardNumber = position+1
val cityApiData = bData.value[position].city
val phoneNumberApiData = bData.value[position].phone
val countryApiData = bData.value[position].country
val breweryTypeApiData = bData.value[position].brewery_type
val countyApiData = bData.value[position].county_province
val postalCodeApiData = bData.value[position].postal_code
val stateApiData = bData.value[position].state
val streetApiData = bData.value[position].street
val apiLastUpdated = bData.value[position].updated_at
val context = LocalContext.current
val lastUpdated = apiLastUpdated?.let { viewModel.dateTextConverter(it) }
val websiteUrlApiData = bData.value[position].website_url
var expanded by remember { mutableStateOf(false) }
val clickableWebsiteText = buildAnnotatedString {
if (websiteUrlApiData != null) {
append(websiteUrlApiData)
}
}
val clickablePhoneNumberText = buildAnnotatedString {
if (phoneNumberApiData != null){
append(phoneNumberApiData)
}
}
Column(
Modifier.padding(10.dp)
) {
//Brewery Card
Card(
modifier = Modifier
.padding(start = 15.dp, end = 15.dp)
// .fillMaxSize()
.clickable(
enabled = true,
onClickLabel = "Expand to view details",
onClick = { expanded = !expanded }
)
.semantics { contentDescription = "Brewery Card" },
backgroundColor = colorResource(id = R.color.light_blue),
contentColor = Color.Black,
border = BorderStroke(0.5.dp, colorResource(id = R.color.pink)),
elevation = 15.dp
) {
Column(verticalArrangement = Arrangement.Center) {
//Number text for position of card
Text(
text = cardNumber.toString(),
modifier = Modifier.padding(15.dp),
fontSize = 10.sp,
)
// Second Row
BreweryTitle(bData = bData, position = position)
// Third Row
// Brewery Details
CardDetails(
cityApiData = cityApiData,
stateApiData = stateApiData,
streetApiData = streetApiData,
countryApiData = countryApiData,
countyApiData = countyApiData,
postalCodeApiData = postalCodeApiData,
breweryTypeApiData = breweryTypeApiData,
lastUpdated = lastUpdated,
expanded = expanded
)
//Fourth Row
Row(horizontalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
){
Column(
modifier = Modifier.padding(
start = 10.dp, end = 10.dp,
top = 15.dp, bottom = 15.dp
),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
//Phone Number Link
LinkBuilder(
clickablePhoneNumberText,
phoneNumberApiData,
modifier = Modifier.padding(bottom = 10.dp)
) {
if (phoneNumberApiData != null) {
viewModel.callNumber(phoneNumberApiData, context)
}
}
//Website Link
LinkBuilder(
clickableWebsiteText,
websiteUrlApiData,
modifier = Modifier.padding(bottom = 15.dp),
intentCall = {
if (websiteUrlApiData != null) {
viewModel.openWebsite(websiteUrlApiData, context)
}
}
)
}
}
}
}
}
}
#Composable
fun CardDetails(
cityApiData: String?,
stateApiData: String?,
streetApiData: String?,
countryApiData: String?,
countyApiData: String?,
postalCodeApiData: String?,
breweryTypeApiData: String?,
lastUpdated: String?,
expanded: Boolean
){
// Third Row
//Brewery Details
Column(
modifier = Modifier.padding(
start = 30.dp, end = 10.dp, top = 25.dp, bottom = 15.dp
),
verticalArrangement = Arrangement.Center
) {
if (expanded) {
Text(text = "City: $cityApiData")
Text(text = "State: $stateApiData")
Text(text = "Street: $streetApiData")
Text(text = "Country: $countryApiData")
Text(text = "County: $countyApiData")
Text(text = "Postal Code: $postalCodeApiData")
Text(text = "Type: $breweryTypeApiData")
Text(text = "Last updated: $lastUpdated")
}
}
}
#Composable
fun BreweryTitle(bData: MutableState<List<BrewData>>, position: Int){
// Second Row
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
// Name of Brewery
Text(
text = bData.value[position].name!!,
modifier = Modifier.padding(start = 15.dp, end = 15.dp),
fontWeight = FontWeight.Bold,
maxLines = 3,
textAlign = TextAlign.Center,
softWrap = true,
style = TextStyle(
color = colorResource(id = R.color.purple_500),
fontStyle = FontStyle.Normal,
fontSize = 17.sp,
fontFamily = FontFamily.SansSerif,
letterSpacing = 2.sp,
)
)
}
}
}
#Composable
fun LinkBuilder(
clickableText: AnnotatedString,
dataText: String?,
modifier: Modifier,
intentCall: (String?) -> Unit
){
if (dataText != null){
ClickableText(
text = clickableText,
modifier = modifier,
style = TextStyle(
textDecoration = TextDecoration.Underline,
letterSpacing = 2.sp
),
onClick = {
intentCall(dataText)
}
)
}
else {
Text(
text = "Sorry, Not Available",
color = Color.Gray,
fontSize = 10.sp
)
}
}
//Gets data from view model
#Composable
fun brewData(
mainViewModel: MainViewModel, search: String?
): DataOrException<List<BrewData>, Boolean, Exception> {
return produceState<DataOrException<List<BrewData>, Boolean, Exception>>(
initialValue = DataOrException(loading = true)
) {
value = mainViewModel.getData(search)
}.value
}
#Composable
fun SortingMenu(sortByName: Boolean, sortByCity: Boolean, sortByAddress: Boolean,) {
var expanded by remember { mutableStateOf(false) }
val items = listOf("Name", "City", "Address")
val disabledValue = "B"
var selectedIndex by remember { mutableStateOf(0) }
Box(
modifier = Modifier
.wrapContentSize(Alignment.TopStart)
) {
Text(
text = "Sort by: ${items[selectedIndex]}",
modifier = Modifier
.clickable(onClick = { expanded = true })
.width(120.dp)
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false // todo: sort list data when clicked
when(selectedIndex){
0 -> sortByName == true
1 -> sortByCity == true
2 -> sortByAddress == true
} }
) {
items.forEachIndexed { index, text ->
DropdownMenuItem(onClick = {
selectedIndex = index
expanded = false
}) {
val disabledText = if (text == disabledValue) {
" (Disabled)"
} else {
""
}
Text(text = text + disabledText)
}
}
}
}
}
//not used
fun sorting(menuList: List<String>, dataList: List<BrewData>, index: Int){
when{
menuList[index] == "Name" -> dataList.sortedBy { it.name }
menuList[index] == "City" -> dataList.sortedBy { it.city }
menuList[index] == "Address" -> dataList.sortedBy { it.address_2 }
}
}
It's really difficult to track this much code especially on my 13 inch screen.
You should move your sort logic to ViewModel or useCase and create a sort function you can call on user interaction such as viewmodel.sort(sortType) and update value of one MutableState with new or use mutableStateListOf and update with sorted list.
Sorting is business logic and i would do it in a class that doesn't contain any Android related dependencies, i use MVI or MVVM so my preference is a UseCase class which i can unit test sorting with any type and a sample list and desired outcomes.
You can do it with Comparatorand Modifier.animateItemPlacement() so it would look even nicer!
I will post an example from Google so you can understand the logic:
#Preview
#OptIn(ExperimentalFoundationApi::class)
#Composable
fun PopularBooksDemo() {
MaterialTheme {
var comparator by remember { mutableStateOf(TitleComparator) }
Column {
Row(
modifier = Modifier.height(IntrinsicSize.Max),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
"Title",
Modifier.clickable { comparator = TitleComparator }
.weight(5f)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
Text(
"Author",
Modifier.clickable { comparator = AuthorComparator }
.weight(2f)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
Text(
"Year",
Modifier.clickable { comparator = YearComparator }
.width(50.dp)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
Text(
"Sales (M)",
Modifier.clickable { comparator = SalesComparator }
.width(65.dp)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
}
Divider(color = Color.LightGray, thickness = Dp.Hairline)
LazyColumn(
Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
val sortedList = PopularBooksList.sortedWith(comparator)
items(sortedList, key = { it.title }) {
Row(
Modifier.animateItemPlacement()
.height(IntrinsicSize.Max),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
it.title,
Modifier.weight(5f)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
Text(
it.author,
Modifier.weight(2f)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
Text(
"${it.published}",
Modifier.width(55.dp)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
Text(
"${it.salesInMillions}",
Modifier.width(65.dp)
.fillMaxHeight()
.padding(4.dp)
.wrapContentHeight(Alignment.CenterVertically),
textAlign = TextAlign.Center
)
}
}
}
}
}
}
private val TitleComparator = Comparator<Book> { left, right ->
left.title.compareTo(right.title)
}
private val AuthorComparator = Comparator<Book> { left, right ->
left.author.compareTo(right.author)
}
private val YearComparator = Comparator<Book> { left, right ->
right.published.compareTo(left.published)
}
private val SalesComparator = Comparator<Book> { left, right ->
right.salesInMillions.compareTo(left.salesInMillions)
}
private val PopularBooksList = listOf(
Book("The Hobbit", "J. R. R. Tolkien", 1937, 140),
Book("Harry Potter and the Philosopher's Stone", "J. K. Rowling", 1997, 120),
Book("Dream of the Red Chamber", "Cao Xueqin", 1800, 100),
Book("And Then There Were None", "Agatha Christie", 1939, 100),
Book("The Little Prince", "Antoine de Saint-Exupéry", 1943, 100),
Book("The Lion, the Witch and the Wardrobe", "C. S. Lewis", 1950, 85),
Book("The Adventures of Pinocchio", "Carlo Collodi", 1881, 80),
Book("The Da Vinci Code", "Dan Brown", 2003, 80),
Book("Harry Potter and the Chamber of Secrets", "J. K. Rowling", 1998, 77),
Book("The Alchemist", "Paulo Coelho", 1988, 65),
Book("Harry Potter and the Prisoner of Azkaban", "J. K. Rowling", 1999, 65),
Book("Harry Potter and the Goblet of Fire", "J. K. Rowling", 2000, 65),
Book("Harry Potter and the Order of the Phoenix", "J. K. Rowling", 2003, 65)
)
private class Book(
val title: String,
val author: String,
val published: Int,
val salesInMillions: Int
)
You have tons of codes and I only see lists, so its hard to guess what's going on, but based on
the list of breweries does not sort
I would advice creating a very simple working app with 1 data class 1 Viewmodel 1 Screen with a LazyColumn and 1 Button.
Consider this:
Your data class
data class Person(
val id: Int,
val name: String
)
Your ViewModel
class MyViewModel {
val peopleList = mutableStateListOf<Person>() // SnapshotStateList
fun onSortButtonClicked() {
// do your sorting logic here
// update your mutable`State`List
}
}
Your Composable Screen
#Composable // I just put the view model as an argument, don't follow it you don't need to
fun MyScreen(viewModel: MyViewModel) {
val myList = viewModel.peopleList
LazyColumn {
items(items = myList, key = { person -> person.id }) { person ->
//.. your item composable //
}
Button(
onClick = { viewModel.onSortButtonClicked() }
)
}
}
It works but its not advisable to use MutableList inside a State or mutableState as any changes you make on its elements won't trigger re-composition, your best way to do it is to manually copy the entire List and create a new one which is again not advisable, thats why SnapshotStateList<T> or mutableStateListOf<T> is not only recommended but the only way to deal with lists in Jetpack Compose development efficiently.
Using SnapshotStateList, any updates (in my experience) such as deleting an element, modifying by doing .copy(..) and re-inserting to the same index will guarantee a re-composition on a Composable that reads that element, in the case of the "working sample code", if I change the name of a person in the SnapshotStateList like peopleList[index] = person.copy(name="Mr Person"), the item composable that reads that person object will re-compose. As for your Sorting problem, I haven't tried it yet so I'm not sure, but I think the list will sort if you simply perform a sorting operation in the SnapshotStateList.
Take everything I said with the grain of salt, though I'm confident with the usage of the SnapshotStateList for the "working sample code", however there are tons of nuances and things happening under the hood that I'm careful not to just simply throw around, but as you said
I am new at this
So am I. I'm confident this is a good starting point dealing with collections/list in jetpack compose.

animation o a lazycolumn android

I have a list with 10 items one of them have this elements "rankingCurrentPlace", "rankingPastPlace" and "isUser:true".
What i need to do its an animation on the lazycolumn if the api esponse is like this
"isUser:true", "rankingPastPlace:3" , "rankingCurrentPlace:7"
i need to show an animation in the list where the row starts in the third place and descend to the seventh place
is there a way to do this?
this is what I actually have
LazyColumn(
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 0.dp),
) {
items(
items = leaderboard,
key = { leaderBoard ->
leaderBoard.rankingPlace
}
) { leaderBoard ->
RowComposable( modifier = Modifier
.fillMaxWidth(),
topicsItem = leaderBoard,)
}
This answer works except when swapping first item with any item even with basic swap function without animation. I think it would be better to ask a new question about why swapping first item doesn't work or if it is bug. Other than that works as expected. If you need to move to items that are not in screen you can lazyListState.layoutInfo.visibleItemsInfo and compare with initial item and scroll to it before animation
1.Have a SnapshotStateList of data to trigger recomposition when we swap 2 items
class MyData(val uuid: String, val value: String)
val items: SnapshotStateList<MyData> = remember {
mutableStateListOf<MyData>().apply {
repeat(20) {
add(MyData( uuid = UUID.randomUUID().toString(), "Row $it"))
}
}
}
2.Function to swap items
private fun swap(list: SnapshotStateList<MyData>, from: Int, to: Int) {
val size = list.size
if (from in 0 until size && to in 0 until size) {
val temp = list[from]
list[from] = list[to]
list[to] = temp
}
}
3.Function to swap items one by one. There is a bug with swapping first item. Even if it's with function above when swapping first item other one moves up without showing animation via Modififer.animateItemPlacement().
#Composable
private fun animatedSwap(
lazyListState: LazyListState,
items: SnapshotStateList<MyData>,
from: Int,
to: Int,
onFinish: () -> Unit
) {
LaunchedEffect(key1 = Unit) {
val difference = from - to
val increasing = difference < 0
var currentValue: Int = from
repeat(abs(difference)) {
val temp = currentValue
if (increasing) {
currentValue++
} else {
currentValue--
}
swap(items, temp, currentValue)
if (!increasing && currentValue == 0) {
delay(300)
lazyListState.scrollToItem(0)
}
delay(350)
}
onFinish()
}
}
4.List with items that have Modifier.animateItemPlacement()
val lazyListState = rememberLazyListState()
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
state = lazyListState,
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 0.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(
items = items,
key = {
it.uuid
}
) {
Row(
modifier = Modifier
.animateItemPlacement(
tween(durationMillis = 200)
)
.shadow(1.dp, RoundedCornerShape(8.dp))
.background(Color.White)
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier
.clip(RoundedCornerShape(10.dp))
.size(50.dp),
painter = painterResource(id = R.drawable.landscape1),
contentScale = ContentScale.FillBounds,
contentDescription = null
)
Spacer(modifier = Modifier.width(10.dp))
Text(it.value, fontSize = 18.sp)
}
}
}
Demo
#OptIn(ExperimentalFoundationApi::class)
#Composable
private fun AnimatedList() {
Column(modifier = Modifier.fillMaxSize()) {
val items: SnapshotStateList<MyData> = remember {
mutableStateListOf<MyData>().apply {
repeat(20) {
add(MyData(uuid = UUID.randomUUID().toString(), "Row $it"))
}
}
}
val lazyListState = rememberLazyListState()
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
state = lazyListState,
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 0.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(
items = items,
key = {
it.uuid
}
) {
Row(
modifier = Modifier
.animateItemPlacement(
tween(durationMillis = 200)
)
.shadow(1.dp, RoundedCornerShape(8.dp))
.background(Color.White)
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier
.clip(RoundedCornerShape(10.dp))
.size(50.dp),
painter = painterResource(id = R.drawable.landscape1),
contentScale = ContentScale.FillBounds,
contentDescription = null
)
Spacer(modifier = Modifier.width(10.dp))
Text(it.value, fontSize = 18.sp)
}
}
}
var fromString by remember {
mutableStateOf("7")
}
var toString by remember {
mutableStateOf("3")
}
var animate by remember { mutableStateOf(false) }
if (animate) {
val from = try {
Integer.parseInt(fromString)
} catch (e: Exception) {
0
}
val to = try {
Integer.parseInt(toString)
} catch (e: Exception) {
0
}
animatedSwap(
lazyListState = lazyListState,
items = items,
from = from,
to = to
) {
animate = false
}
}
Row(modifier = Modifier.fillMaxWidth()) {
TextField(
value = fromString,
onValueChange = {
fromString = it
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
TextField(
value = toString,
onValueChange = {
toString = it
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
}
Button(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
onClick = {
animate = true
}
) {
Text("Swap")
}
}
}
Edit: Animating with Animatable
Another method for animating is using Animatable with Integer vector.
val IntToVector: TwoWayConverter<Int, AnimationVector1D> =
TwoWayConverter({ AnimationVector1D(it.toFloat()) }, { it.value.toInt() })
val coroutineScope = rememberCoroutineScope()
val animatable = remember { Animatable(0, IntToVector) }
And can be used as
private fun alternativeAnimate(
from: Int,
to: Int,
coroutineScope: CoroutineScope,
animatable: Animatable<Int, AnimationVector1D>,
items: SnapshotStateList<MyData>
) {
val difference = from - to
var currentValue: Int = from
coroutineScope.launch {
animatable.snapTo(from)
animatable.animateTo(to,
tween(350 * abs(difference), easing = LinearEasing),
block = {
val nextValue = this.value
if (abs(currentValue -nextValue) ==1) {
swap(items, currentValue, nextValue)
currentValue = nextValue
}
}
)
}
}
on button click, i'm getting values from TextField fo i convert from String
Button(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
onClick = {
val from = try {
Integer.parseInt(fromString)
} catch (e: Exception) {
0
}
val to = try {
Integer.parseInt(toString)
} catch (e: Exception) {
0
}
alternativeAnimate(from, to, coroutineScope, animatable, items)
}
) {
Text("Swap")
}
Result
I suggest you to get your items from a data class. If your other items does not contain the variables you mentioned you can make them nullable in data class and put a condition checker in your lazycolumn
Like this
data class Items(
val otherItems: Other,
val rankingCurrentPlace: Int?,
val rankingLastPlace: Int?,
val isUser: Boolean?
)
Then you can make a list from this data class and pass it to lazycolumn
LazyColumn{
items(list){
(elements with condition)
}
}

Jetpack Compose - Search bar won't allow me to search and the cursor will not show up

I have a custom search bar will not allow me to place a cursor and type text into it. Before adding the viewmodel and state, I was able to have the TextField work and allow typing text into it.
I've tried using state variables within the composable instead of separating the logic into the view model and unfortunatly recieved the same result. I have a feeling it's something simple that I'm missing but can't quite find it.
Custom Search Bar:
#Composable
fun SearchBar(
modifier: Modifier,
viewModel: ToolSetListViewModel = hiltViewModel()
){
Surface (
modifier = modifier
.fillMaxWidth()
.height(74.dp)
.padding(20.dp, 15.dp, 20.dp, 0.dp),
elevation = 10.dp,
color = MaterialTheme.colors.primary,
shape = RoundedCornerShape(25)
){
TextField(
modifier = modifier
.fillMaxWidth(),
value = viewModel.searchText,
onValueChange = {
viewModel.onEvent(ToolSetListEvent.OnSearchToolSet(it))
},
placeholder = {
Text(
modifier = modifier
.alpha(ContentAlpha.medium),
text = "Search...",
color = White
)
},
textStyle = TextStyle(
fontSize = MaterialTheme.typography.subtitle1.fontSize,
),
singleLine = true,
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
cursorColor = White
)
)
}
Screen:
#Composable
fun ToolSetListScreen(
onNavigate: (UiEvent.Navigate) -> Unit,
viewModel: ToolSetListViewModel = hiltViewModel()
) {
val toolSets = viewModel.toolSets.collectAsState(initial = emptyList())
LaunchedEffect(key1 = true) {
viewModel.uiEvent.collect { event ->
when(event) {
is UiEvent.Navigate -> onNavigate(event)
}
}
}
Scaffold (
floatingActionButton = {
FloatingActionButton(onClick = {
viewModel.onEvent(ToolSetListEvent.OnAddToolSetClick)
}) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Add")
}
}
) {
SearchBar(
modifier = Modifier,
)
LazyColumn(
modifier = Modifier.fillMaxSize()
.padding(0.dp, 20.dp)
) {
items(toolSets.value) { toolset ->
ToolSetItem(
toolSet = toolset,
onEvent = viewModel::onEvent,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clickable {
viewModel.onEvent(ToolSetListEvent.OnToolSetClick(toolset))
}
)
}
}
}
}
ViewModel:
#HiltViewModel
class ToolSetListViewModel #Inject constructor(
private val repository: ToolSetRepository
): ViewModel() {
val toolSets = repository.getAllToolSets()
private val _uiEvent = Channel<UiEvent>()
val uiEvent = _uiEvent.receiveAsFlow()
var searchText by mutableStateOf("")
private set
fun onEvent(event: ToolSetListEvent) {
when(event) {
is ToolSetListEvent.OnToolSetClick -> {
sendUiEvent(UiEvent.Navigate(Routes.ADD_EDIT_TOOL_SET + "?PONumber=${event.toolSet.PONumber}"))
}
is ToolSetListEvent.OnDeleteToolSetClick -> {
viewModelScope.launch {
repository.deleteToolSet(event.toolset)
}
}
is ToolSetListEvent.OnAddToolSetClick -> {
sendUiEvent(UiEvent.Navigate(Routes.ADD_EDIT_TOOL_SET))
}
is ToolSetListEvent.OnSearchToolSet -> {
viewModelScope.launch {
if (event.searchText.isNotBlank()) {
searchText = event.searchText
repository.getToolSetByPO(event.searchText)
}
}
}
}
}
private fun sendUiEvent(event: UiEvent) {
viewModelScope.launch {
_uiEvent.send(event)
}
}
MainActivity:
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
PunchesManagerTheme {
val navController = rememberNavController()
Scaffold (
content = {
Navigation(navController)
},
bottomBar = { BottomNavigationBar(navController = navController) },
)
}
}
}
}
#Composable
fun BottomNavigationBar(navController: NavHostController) {
BottomNavigation {
val backStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = backStackEntry?.destination?.route
NavBarItems.bottomNavItem.forEach { navItem ->
BottomNavigationItem(selected = currentRoute == navItem.route, onClick = {
navController.navigate(navItem.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = false
}
launchSingleTop = true
restoreState = true
}
},
icon = {
Icon(imageVector = navItem.icon,
contentDescription = navItem.name)
},
label = {
Text(text = navItem.name)
},
)
}
}
}
Any suggestions on what the issue may be?
I think I found the fix!
I adjusted the layout of my scaffoled in my ToolSetListScreen:
Scaffold (
content = {
SearchBar(
modifier = Modifier,
)
LazyColumn(
modifier = Modifier.fillMaxSize()
.padding(0.dp, 75.dp)
) {
items(toolSets.value) { toolset ->
ToolSetItem(
toolSet = toolset,
onEvent = viewModel::onEvent,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clickable {
viewModel.onEvent(ToolSetListEvent.OnToolSetClick(toolset))
}
)
}
}
},
floatingActionButton = {
FloatingActionButton(onClick = {
viewModel.onEvent(ToolSetListEvent.OnAddToolSetClick)
}) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Add")
}
}
)
}
and this seemed to work.

Manage state in Jetpack Compose

In my viewModel I have "state" for every single screen. e.g.
class MainState(val commonState: CommonState) {
val text = MutableStateFlow("text")
}
I pass viewModel to my JetpackCompose screen.
#Composable
fun MainScreen(text: String, viewModel: HomeViewModel) {
val textState = remember { mutableStateOf(TextFieldValue()) }
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = viewModel.state.mainState.text.value,
color = Color.Blue,
fontSize = 40.sp
)
Button(
onClick = { viewModel.state.mainState.text.value = "New text" },
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Green
),
modifier = Modifier.padding(16.dp)
) {
Text(text)
}
TextField(
value = textState.value,
onValueChange = { textState.value = it },
label = { Text("Input text") }
)
}
}
When I click button I change value of state and I expect UI will update but it does not. I have to click on TextField and then text in TextView updates.
Any suggestion why UI does not update automatically?
That's how I pass components and start whole screen in startActivity;
class HomeActivity : ComponentActivity() {
private val viewModel by viewModel<HomeViewModel>()
private val homeState: HomeState get() = viewModel.state
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RateMeAppTheme {
ContentScreen(viewModel, homeState)
}
}
}
}
In this simple case u should use mutableStateOf("text") in class MainState instead of mutableStateFlow
class MainState(val commonState: CommonState) {
val text = mutableStateOf("text")
}
Using MutableStateFlow
To use MutableStateFlow (which is not required in the current scenario) , we need to collect the flow.
Like the following:-
val state = viewModel.mainState.text.collectAsState() // we can collect a stateflow as state in a composable function
Then we can use the observed state value in the Text using:-
Text(text = state.value, ..)
Finally your composable function should look like:-
#Composable
fun MainScreen(text: String, viewModel: HomeViewModel) {
val textState = remember { mutableStateOf(TextFieldValue()) }
val state = viewModel.mainState.text.collectAsState()
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = state.value,
color = Color.Blue,
fontSize = 40.sp
)
Button(
onClick = { viewModel.mainState.text.value = "New text" },
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Green
),
modifier = Modifier.padding(16.dp)
) {
Text(text)
}
TextField(
value = textState.value,
onValueChange = { textState.value = it },
label = { Text("Input text") }
)
}
}

Categories

Resources