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.
I have 2 Radio Buttons to change the text color of a text (red text, hardcoded).
But i cant get the Text(color = Color.colorsTextRadio) to work.
I know it says it is a string but who do i get the Red or Green to convert to color.
If i have done something that could be better in thecode please tell because I'm a beginner.
#Composable
fun MainScreen() {
/**
* Text
*/
var text by remember {
mutableStateOf("test")
}
// Event handler
val onTextChange = { value: String ->
text = value
}
/**
* Colors
*/
val colors = listOf("Red", "Green")
var colorsTextRadio by remember {
mutableStateOf(colors[0])
}
// Event Handler
val onTextColorChange = { value: String ->
colorsTextRadio = value
}
Log.d("TAG", "MainScreen: colorsTextRadio $colorsTextRadio")
Column(modifier = Modifier.padding(6.dp)) {
TextField(value = text, onValueChange = onTextChange)
Text(text = text.replace("\n", " "), maxLines = 1, color = Color.Red)
RadioButtonGroup(colors = colors, colorsTextRadio = colorsTextRadio, onClick = onTextColorChange)
}
}
#Composable
fun RadioButtonGroup(
colors: List<String>,
colorsTextRadio: String,
onClick: (String) -> Unit
) {
Column(modifier = Modifier.selectableGroup()) {
colors.forEach { label ->
Row(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = (colorsTextRadio == label),
onClick = { onClick.invoke(label) },
role = Role.RadioButton
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
modifier = Modifier.padding(end = 16.dp),
selected = (colorsTextRadio == label),
onClick = null // null recommended for accessibility with screen readers
)
Text(text = label)
}
}
}
}
You can define a data class:
data class ColorLabel(
val label: String,
val color: Color
)
val colors = listOf(
ColorLabel("Red",Red),
ColorLabel("Green", Green))
var colorsTextRadio by remember { mutableStateOf(colors[0].label) }
var colorsText by remember { mutableStateOf(colors[0].color) }
Then apply them to your Composables:
Text(text = text.replace("\n", " "),
maxLines = 1,
color = colorsText)
Column(modifier = Modifier.selectableGroup()) {
colors.forEach { colorlabel->
Row(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = (colorsTextRadio == colorlabel.label),
onClick = {
colorsTextRadio = colorlabel.label
colorsText = colorlabel.color
},
role = Role.RadioButton
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
modifier = Modifier.padding(end = 16.dp),
selected = (colorsTextRadio == colorlabel.label),
onClick = null // null recommended for accessibility with screen readers
)
Text(text = colorlabel.label)
}
}
}
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
}
Currently I'm trying to find an easy way to implement a step progress bar with compose like this:
Does anyone have experience with that? Is there maybe a good library?
I don't think you need a library from this one, a simple and quick 'do it yourself' solution could be something like this:
#Composable
fun StepsProgressBar(modifier: Modifier = Modifier, numberOfSteps: Int, currentStep: Int) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically
) {
for (step in 0..numberOfSteps) {
Step(
modifier = Modifier.weight(1F),
isCompete = step < currentStep,
isCurrent = step == currentStep
)
}
}
}
#Composable
fun Step(modifier: Modifier = Modifier, isCompete: Boolean, isCurrent: Boolean) {
val color = if (isCompete || isCurrent) Color.Red else Color.LightGray
val innerCircleColor = if (isCompete) Color.Red else Color.LightGray
Box(modifier = modifier) {
//Line
Divider(
modifier = Modifier.align(Alignment.CenterStart),
color = color,
thickness = 2.dp
)
//Circle
Canvas(modifier = Modifier
.size(15.dp)
.align(Alignment.CenterEnd)
.border(
shape = CircleShape,
width = 2.dp,
color = color
),
onDraw = {
drawCircle(color = innerCircleColor)
}
)
}
}
#Preview
#Composable
fun StepsProgressBarPreview() {
val currentStep = remember { mutableStateOf(1) }
StepsProgressBar(modifier = Modifier.fillMaxWidth(), numberOfSteps = 5, currentStep = currentStep.value)
}
This will be the result:
I have created a similar function that takes customisable params.
#Composable
fun Track(
items: Int,
brush: (from: Int) -> Brush,
modifier: Modifier = Modifier,
lineWidth: Dp = 1.dp,
pathEffect: ((from: Int) -> PathEffect?)? = null,
icon: #Composable (index: Int) -> Unit,
) {
Box(
modifier = modifier,
contentAlignment = Alignment.Center,
) {
Canvas(
modifier = Modifier
.fillMaxWidth()
.zIndex(-1f)
) {
val width = drawContext.size.width
val height = drawContext.size.height
val yOffset = height / 2
val itemWidth = width / items
var startOffset = itemWidth / 2
var endOffset = startOffset
val barWidth = lineWidth.toPx()
repeat(items - 1) {
endOffset += itemWidth
drawLine(
brush = brush.invoke(it),
start = Offset(startOffset, yOffset),
end = Offset(endOffset, yOffset),
strokeWidth = barWidth,
pathEffect = pathEffect?.invoke(it)
)
startOffset = endOffset
}
}
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically,
) {
repeat(items) { index ->
Box(
contentAlignment = Alignment.Center,
) {
icon.invoke(index)
}
}
}
}
}
Add jitpack in your build.gradle:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Add compose-stepper library to your app/build.gradle
dependencies {
implementation 'com.github.maryamrzdh:compose-stepper:1.0.0-beta01'
}
Add a Stepper in a composable function
#Composable
fun StepperView() {
val numberOfSteps = 4
var currentStep by rememberSaveable { mutableStateOf(1) }
val titleList= arrayListOf("Step 1","Step 2","Step 3","Step 4")
Stepper(
modifier = Modifier.fillMaxWidth(),
numberOfSteps = numberOfSteps,
currentStep = currentStep,
stepDescriptionList = titleList,
unSelectedColor= Color.LightGray,
selectedColor = Color.Blue,
isRainbow = false
)
For more info go to Stepper using JetPack Compose
I have a String "(+91)". How do I animate it such that on some action, "(+91)" fades in gradually, and on some other action "(+91)" fades out gradually. I am using "(+91)" as prefix in my Textfield, with the help of visualTransformation.
This is the code I'm using for my Textfield:
TextField(
value = query3.value,
onValueChange = { newValue ->
query3.value = newValue
mobErrorVisible.value = false
},
visualTransformation = if (showCode){
PrefixTransformation("(+91)")} //Animate (+91)
else
PrefixTransformation(""),
label = {
Text(
"Mobile Number",
color = colorResource(id = R.color.bright_green),
fontFamily = FontFamily(Font(R.font.poppins_regular)),
fontSize = with(LocalDensity.current) { dimensionResource(id = R.dimen._12ssp).toSp() })
},
interactionSource = interactionSource,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
textStyle = TextStyle(
textAlign = TextAlign.Start,
color = colorResource(id = R.color.bright_green),
fontFamily = FontFamily(Font(R.font.poppins_regular)),
fontSize = with(LocalDensity.current) { dimensionResource(id = R.dimen._16ssp).toSp() }
),
modifier = Modifier
.drawBehind {
val strokeWidth = indicatorWidth.value * density
val y = size.height - strokeWidth / 2
drawLine(
indicatorColor,
Offset(TextFieldPadding.toPx(), y),
Offset(size.width - TextFieldPadding.toPx(), y),
strokeWidth
)
}
.focusRequester(focusRequester)
.onFocusChanged { showCode = (it.isFocused || query3.value != "")}
.constrainAs(phone) {
top.linkTo(glPhone)
bottom.linkTo(glPhoneBottom)
start.linkTo(glLeft)
end.linkTo(glRight)
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
focusedIndicatorColor = Transparent,
unfocusedIndicatorColor = Transparent,
disabledIndicatorColor = Transparent
)
)
This is my PrefixTransformation class:
class PrefixTransformation(val prefix: String) : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
return PrefixFilter(text, prefix)
}
}
This is my PrefixFilter() function:
fun PrefixFilter(number: AnnotatedString, prefix: String): TransformedText {
var out = prefix + " " + number.text
val prefixOffset = prefix.length
val numberOffsetTranslator = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
return offset + prefixOffset
}
override fun transformedToOriginal(offset: Int): Int {
if (offset <= prefixOffset-1) return prefixOffset
return offset - prefixOffset
}
}
return TransformedText(AnnotatedString(out), numberOffsetTranslator)
}
We can animate color as:
val color = remember { Animatable(Color.Gray) }
LaunchedEffect(ok) {
color.animateTo(if (ok) Color.Green else Color.Red)
}
Box(Modifier.fillMaxSize().background(color.value))
But how do we animate a String?
What you need is the animatedVisibility composable.
Here is an example where the visibility of the text is controlled by the button
Box(
modifier = Modifier
.fillMaxSize()
) {
var visible by remember { mutableStateOf(false) }
Button(
modifier = Modifier.align(Alignment.TopCenter),
onClick = {
visible = !visible
}
) {
Text("Toggle Visibility")
}
val animationDuration = 2000
AnimatedVisibility(
modifier = Modifier.align(Alignment.BottomCenter),
visible = visible,
enter = fadeIn(animationSpec = tween(durationMillis = animationDuration)),
exit = fadeOut(animationSpec = tween(durationMillis = animationDuration))
) {
Text("ABC")
}
}
A sensible solution would be to use a separate Composable for the country code. That way you can wrap the Composable in something like crossfade or just AnimatedVisibility (Experimental as of compose 1.0.0-beta07)