Box overlay in jetpack compose - android

I want to create a composable (shown in below image) where one box is larger and one smaller box is placed at bottom center of large box and bottom line of large box is passing through center of small box. How do I do that?

You could use a custom layout:
#Composable
fun Boxes(
modifier: Modifier = Modifier,
content: #Composable () -> Unit,
) {
Layout(
modifier = modifier,
content = content,
) { measurables, constraints ->
val largeBox = measurables[0]
val smallBox = measurables[1]
val looseConstraints = constraints.copy(
minWidth = 0,
minHeight = 0,
)
val largePlaceable = largeBox.measure(looseConstraints)
val smallPlaceable = smallBox.measure(looseConstraints)
layout(
width = constraints.maxWidth,
height = constraints.maxHeight
) {
largePlaceable.placeRelative(0, 0)
smallPlaceable.placeRelative(
x = (constraints.maxWidth - smallPlaceable.width) / 2,
y = largePlaceable.height - smallPlaceable.height / 2
)
}
}
}
#Preview(widthDp = 420, heightDp = 720)
#Composable
fun BoxesPreview() {
ComposePlaygroundTheme() {
Surface(modifier = Modifier.fillMaxSize()) {
Boxes(
modifier = Modifier.fillMaxWidth()
) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(128.dp)
.background(Color.Green)
)
Box(
modifier = Modifier
.width(128.dp)
.height(64.dp)
.background(Color.Red)
)
}
}
}
}
Edit: restricting the boxes height, use this
#Composable
fun Boxes(
modifier: Modifier = Modifier,
content: #Composable () -> Unit,
) {
Layout(
modifier = modifier,
content = content,
) { measurables, constraints ->
val largeBox = measurables[0]
val smallBox = measurables[1]
val looseConstraints = constraints.copy(
minWidth = 0,
minHeight = 0,
)
val largePlaceable = largeBox.measure(looseConstraints)
val smallPlaceable = smallBox.measure(looseConstraints)
layout(
width = constraints.maxWidth,
height = largePlaceable.height + smallPlaceable.height / 2,
) {
largePlaceable.placeRelative(
x = 0,
y = 0,
)
smallPlaceable.placeRelative(
x = (constraints.maxWidth - smallPlaceable.width) / 2,
y = largePlaceable.height - smallPlaceable.height / 2
)
}
}
}
#Preview(widthDp = 420, heightDp = 720)
#Composable
fun BoxesPreview() {
ComposePlaygroundTheme {
Surface(modifier = Modifier.fillMaxSize()) {
Column {
Text(
text = "Before",
modifier = Modifier.padding(all = 16.dp)
)
Boxes(
modifier = Modifier.fillMaxWidth()
) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(128.dp)
.background(Color.Green)
)
Box(
modifier = Modifier
.width(128.dp)
.height(64.dp)
.background(Color.Red)
)
}
Text(
text = "After",
modifier = Modifier.padding(all = 16.dp)
)
}
}
}
}

Related

Compose ModalBottomSheet with dynamic height and scrollable column could not dragging down when there is no extra space

What I want
Top fixed item with status bar padding and adaptive radius
Bottom fixed item with navigation bar padding
Adaptive center item, have enough room => Not scrollable, if not => scrollable
Current status
For full demo click this link
Only problem here is when there is no extra space, and we are dragging the scrollable list.
I think it's a bug, because everything is fine except the scrollable column.
window.height - sheetContent.height >= statusBarHeight
Everything is fine.
window.height - sheetContent.height < statusBarHeight
Dragging top fixed item or bottom fixed item, scroll still acting well.
Dragging the scrollable list, sheet pops back to top when the sheetState.offset is approaching statusBarHeight
Test youself
You can test it with these 3 functions, for me, I'm using Pixel 2 Emulator, itemCount at 18,19 could tell the difference.
#Composable
fun CEModalBottomSheet(
sheetState: ModalBottomSheetState,
onCloseDialogClicked: () -> Unit,
title: String = "BottomSheet Title",
toolbarElevation: Dp = 0.dp,
sheetContent: #Composable ColumnScope.() -> Unit,
) {
val density = LocalDensity.current
val sheetOffset = sheetState.offset
val statusBar = WindowInsets.statusBars.asPaddingValues()
val shapeRadius by animateDpAsState(
if (sheetOffset.value < with(density) { statusBar.calculateTopPadding().toPx() }) {
0.dp
} else 12.dp
)
val dynamicStatusBarPadding by remember {
derivedStateOf {
val statusBarHeightPx2 = with(density) { statusBar.calculateTopPadding().toPx() }
val offsetValuePx = sheetOffset.value
if (offsetValuePx >= statusBarHeightPx2) {
0.dp
} else {
with(density) { (statusBarHeightPx2 - offsetValuePx).toDp() }
}
}
}
ModalBottomSheetLayout(
sheetState = sheetState,
sheetShape = RoundedCornerShape(topStart = shapeRadius, topEnd = shapeRadius),
content = {},
sheetContent = {
Column(modifier = Modifier.fillMaxWidth()) {
TopTitleItemForDialog(
title = title,
elevation = toolbarElevation,
topPadding = dynamicStatusBarPadding,
onClick = onCloseDialogClicked
)
sheetContent()
}
})
}
#Composable
fun TopTitleItemForDialog(
title: String,
elevation: Dp = 0.dp,
topPadding: Dp = 0.dp,
onClick: () -> Unit
) {
Surface(
modifier = Modifier.fillMaxWidth(),
color = Color.LightGray,
elevation = elevation
) {
Row(
modifier = Modifier.padding(top = topPadding),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(modifier = Modifier.size(16.dp))
Text(
text = title,
maxLines = 1,
modifier = Modifier.weight(1f)
)
IconButton(onClick = onClick) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = stringResource(R.string.cancel),
tint = Color.Gray,
modifier = Modifier.size(24.dp)
)
}
}
}
}
class SheetPaddingTestActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.statusBarColor = android.graphics.Color.TRANSPARENT
window.navigationBarColor = android.graphics.Color.TRANSPARENT
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
Box(
Modifier
.fillMaxSize()
.background(Color.Green), contentAlignment = Alignment.Center
) {
var itemCount by remember { mutableStateOf(20) }
val state = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden) { false }
val scope = rememberCoroutineScope()
Text("显示弹窗", modifier = Modifier.clickable {
scope.launch { state.animateTo(ModalBottomSheetValue.Expanded) }
})
CEModalBottomSheet(sheetState = state,
onCloseDialogClicked = {
scope.launch {
state.hide()
}
}, sheetContent = {
Column(
Modifier
.verticalScroll(rememberScrollState())
.weight(1f, fill = false)
.padding(horizontal = 16.dp),
) {
repeat(itemCount) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(30.dp)
.background(Color.Blue.copy(alpha = 1f - it * 0.04f))
)
}
}
CompositionLocalProvider(
LocalContentColor.provides(Color.White)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colors.primary)
.padding(vertical = 12.dp)
.navigationBarsPadding(),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(modifier = Modifier.weight(1f),
onClick = {
itemCount = max(itemCount - 1, 0)
}) {
Icon(Icons.Default.KeyboardArrowLeft, "")
}
Text(
modifier = Modifier.weight(1f), text = "$itemCount",
textAlign = TextAlign.Center
)
IconButton(modifier = Modifier.weight(1f),
onClick = {
itemCount++
}) {
Icon(Icons.Default.KeyboardArrowRight, "")
}
}
}
}
)
}
}
}
}

How to exclude a child composable from parent alpha value change?

In the shopping list item composable, I am reducing the alpha value on the whole item by changing the alpha value on it's parent Row composable, but I want to exclude a child Icon composable from receiving the parent Row's alpha change and retain a 100% alpha value. I set the modifier on the child Icon to alpha(1f), but it is not working. The alpha change on the parent is also propagating to the child despite this. Is it possible exclude the child from the parent's alpha change?
Composable
#Composable
fun ShoppingListScreenItem(
rowModifier: Modifier = Modifier,
item: ShoppingListItem,
mainViewModel: ShoppingListScreenViewModel,
onNavigateToAddEditItemScreenFromItemStrip: (ShoppingListItem) -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 3.dp, bottom = 5.dp)
.then(rowModifier)
.alpha(if (item.isItemDisabled) 0.35f else 1f)
.clickable {
onNavigateToAddEditItemScreenFromItemStrip(item)
},
verticalAlignment = Alignment.CenterVertically,
) {
...
if(mainViewModel.shoppingListState.value!!.sortOrder != "Custom" && !item.isInCart) {
//I want to exclude this child composable
IconToggleButton(
checked = item.isItemDisabled,
onCheckedChange = {
scope.launch {
mainViewModel.updateShoppingListItemDisabledInDb(item, it)
}
},
) {
Icon(
modifier = Modifier.alpha(1f).size(26.dp),
painter = painterResource(id = R.drawable.baseline_disabled_visible_24),
contentDescription = "Toggle disable the item strip",
)
}
}
}
}
This can be achieved using Layout and placeable.placeWithLayer and Modifier.layoutId to select which Composable is to be used with default alpha as.
This is a custom Column, you can customize Layout as required, purpose is to show Modifier.layoutId usage and Placeable.placeRelativeWithLayer to apply any desired graphic layer property to specific Composable in layout phase.
Result
Usage
MyLayout(
alpha = .5f
) {
Text("Default Alpha", fontSize = 20.sp)
Text("Default Alpha", fontSize = 20.sp)
Text("Custom Alpha", fontSize = 20.sp), modifier = Modifier.layoutId("full_alpha"))
Text("Default Alpha", fontSize = 20.sp)
Image(painter = painterResource(id = R.drawable.landscape5), contentDescription = "")
}
Implementation
#Composable
private fun MyLayout(
modifier: Modifier = Modifier,
alpha: Float = 1f,
content: #Composable () -> Unit
) {
val measurePolicy = MeasurePolicy { measurables, constraints ->
val fullAlphaIndex = measurables.indexOfFirst {
it.layoutId == "full_alpha"
}
val placeablesWidth = measurables.map { measurable ->
measurable.measure(constraints)
}
val hasBoundedWidth = constraints.hasBoundedWidth
val hasFixedWidth = constraints.hasFixedWidth
val width =
if (hasBoundedWidth && hasFixedWidth) constraints.maxWidth
else placeablesWidth.maxOf { it.width }
val height = placeablesWidth.sumOf {
it.height
}
var posY = 0
layout(width, height) {
placeablesWidth.forEachIndexed { index, placeable ->
placeable.placeRelativeWithLayer(0, posY) {
if (index == fullAlphaIndex) {
this.alpha = 1f
} else {
this.alpha = alpha
}
}
posY += placeable.height
}
}
}
Layout(
modifier = modifier,
content = content,
measurePolicy = measurePolicy
)
}
If you wish to create a Row you need to place items one after other horizontally instead of increasing y position
Result
#Composable
fun MyLayout(
modifier: Modifier = Modifier,
alpha: Float = 1f,
content: #Composable () -> Unit
) {
val measurePolicy = MeasurePolicy { measurables, constraints ->
val fullAlphaIndex = measurables.indexOfFirst {
it.layoutId == "full_alpha"
}
val placeablesWidth = measurables.map { measurable ->
measurable.measure(
constraints.copy(
minWidth = 0,
maxWidth = Constraints.Infinity,
minHeight = 0,
maxHeight = Constraints.Infinity
)
)
}
val hasBoundedWidth = constraints.hasBoundedWidth
val hasFixedWidth = constraints.hasFixedWidth
val hasBoundedHeight = constraints.hasBoundedHeight
val hasFixedHeight = constraints.hasFixedHeight
val width =
if (hasBoundedWidth && hasFixedWidth) constraints.maxWidth
else placeablesWidth.sumOf { it.width }.coerceAtMost(constraints.maxWidth)
val height =
if (hasBoundedHeight && hasFixedHeight) constraints.maxHeight
else placeablesWidth.maxOf { it.height }.coerceAtMost(constraints.maxHeight)
var posX = 0
layout(width, height) {
placeablesWidth.forEachIndexed { index, placeable ->
placeable.placeRelativeWithLayer(posX, 0) {
if (index == fullAlphaIndex) {
this.alpha = 1f
} else {
this.alpha = alpha
}
}
posX += placeable.width
}
}
}
Layout(
modifier = modifier,
content = content,
measurePolicy = measurePolicy
)
}
Same usage but this time with Icons
MyLayout(
modifier = Modifier.drawChecker(),
alpha = .4f
) {
Icon(
imageVector = Icons.Default.NotificationsActive,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.background(Color.Red, CircleShape)
.size(100.dp)
.padding(10.dp)
)
Icon(
imageVector = Icons.Default.NotificationsActive,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.background(Color.Red, CircleShape)
.size(100.dp)
.padding(10.dp)
)
Icon(
imageVector = Icons.Default.NotificationsActive,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.layoutId("full_alpha")
.background(Color.Red, CircleShape)
.size(100.dp)
.padding(10.dp)
)
Icon(
imageVector = Icons.Default.NotificationsActive,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.background(Color.Red, CircleShape)
.size(100.dp)
.padding(10.dp)
)
}
Checker Modifier if anyone wonders is as
fun Modifier.drawChecker() = this.then(
drawBehind {
val width = this.size.width
val height = this.size.height
val checkerWidth = 10.dp.toPx()
val checkerHeight = 10.dp.toPx()
val horizontalSteps = (width / checkerWidth).toInt()
val verticalSteps = (height / checkerHeight).toInt()
for (y in 0..verticalSteps) {
for (x in 0..horizontalSteps) {
val isGrayTile = ((x + y) % 2 == 1)
drawRect(
color = if (isGrayTile) Color.LightGray else Color.White,
topLeft = Offset(x * checkerWidth, y * checkerHeight),
size = Size(checkerWidth, checkerHeight)
)
}
}
}
)

adding text above icon in jetpack compose

Is there any way how I can show a little description above specific icon in Jetpack Compose like in this picture?
It's called speech or tooltip bubble. You can create this or any shape using GenericShape or adding RoundedRect.
Column(
modifier = Modifier
.fillMaxSize()
.padding(10.dp)
) {
var showToolTip by remember {
mutableStateOf(false)
}
Spacer(modifier = Modifier.height(100.dp))
val triangleShape = remember {
GenericShape { size: Size, layoutDirection: LayoutDirection ->
val width = size.width
val height = size.height
lineTo(width / 2, height)
lineTo(width, 0f)
lineTo(0f, 0f)
}
}
Box {
if (showToolTip) {
Column(modifier = Modifier.offset(y = (-48).dp)) {
Box(
modifier = Modifier
.clip(RoundedCornerShape(10.dp))
.shadow(2.dp)
.background(Color(0xff26A69A))
.padding(8.dp),
) {
Text("Hello World", color = Color.White)
}
Box(
modifier = Modifier
.offset(x = 15.dp)
.clip(triangleShape)
.width(20.dp)
.height(16.dp)
.background(Color(0xff26A69A))
)
}
}
IconButton(
onClick = { showToolTip = true }
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "null",
Modifier
.background(Color.Red, CircleShape)
.padding(4.dp)
)
}
}
}
If you need shadow or border that must be a single shape you need to build it with GenericShape. You can check my answer out and library i built.
The sample below is simplified version of library, with no Modifier.layout which is essential for setting space reserved for arrow and setting padding correctly instead of creating another Box with Padding
Result
fun getBubbleShape(
density: Density,
cornerRadius: Dp,
arrowWidth: Dp,
arrowHeight: Dp,
arrowOffset: Dp
): GenericShape {
val cornerRadiusPx: Float
val arrowWidthPx: Float
val arrowHeightPx: Float
val arrowOffsetPx: Float
with(density) {
cornerRadiusPx = cornerRadius.toPx()
arrowWidthPx = arrowWidth.toPx()
arrowHeightPx = arrowHeight.toPx()
arrowOffsetPx = arrowOffset.toPx()
}
return GenericShape { size: Size, layoutDirection: LayoutDirection ->
val rectBottom = size.height - arrowHeightPx
this.addRoundRect(
RoundRect(
rect = Rect(
offset = Offset.Zero,
size = Size(size.width, rectBottom)
),
cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx)
)
)
moveTo(arrowOffsetPx, rectBottom)
lineTo(arrowOffsetPx + arrowWidthPx / 2, size.height)
lineTo(arrowOffsetPx + arrowWidthPx, rectBottom)
}
}
Then create a Bubble Composable, i set static values but you can set these as parameters
#Composable
private fun Bubble(
modifier: Modifier = Modifier,
text: String
) {
val density = LocalDensity.current
val arrowHeight = 16.dp
val bubbleShape = remember {
getBubbleShape(
density = density,
cornerRadius = 12.dp,
arrowWidth = 20.dp,
arrowHeight = arrowHeight,
arrowOffset = 30.dp
)
}
Box(
modifier = modifier
.clip(bubbleShape)
.shadow(2.dp)
.background(Color(0xff26A69A))
.padding(bottom = arrowHeight),
contentAlignment = Alignment.Center
) {
Box(modifier = Modifier.padding(8.dp)) {
Text(
text = text,
color = Color.White,
fontSize = 20.sp
)
}
}
}
You can use it as in this sample. You need to change offset of Bubble to match position of ImageButton
Column(
modifier = Modifier
.fillMaxSize()
.padding(10.dp)
) {
var showToolTip by remember {
mutableStateOf(false)
}
Spacer(modifier = Modifier.height(100.dp))
Box {
if (showToolTip) {
Bubble(
modifier = Modifier.offset(x = (-15).dp, (-52).dp),
text = "Hello World"
)
}
IconButton(
onClick = { showToolTip = true }
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "null",
Modifier
.background(Color.Red, CircleShape)
.padding(4.dp)
)
}
}
}
You can use a Box. The children of the Box layout will be stacked over each other.
Box{
Text(text = "Text Above Icon", modifier = text alignment)
Icon(... , modifier = icon alignment)
}
Text can be added above an icon in Jetpack Compose by using a combination of the Row and Column composables. The Row composable lays out its children in a single row while the Column composable lays out its children in a single column. To add text above the icon, the Row composable should be used first, followed by the Column composable. This will allow the text to be placed on the top of the icon. For example, the following code will add text above an icon:
Row {
Text(text = "Text Above Icon")
Column {
Icon(... )
}
}

Jetpack compose width of row children

In Jetpack Compose, How to find the width of each child of a Row?
I tried using onGloballyPositioned like below, but the size is wrong.
Also, not sure if this is the optimal one.
I need the width of each child and further processing will be done based on that, the below is a simplified code for example.
#Composable
fun MyTabSample() {
MyCustomRow(
items = listOf("Option 1 with long", "Option 2 with", "Option 3"),
)
}
#Composable
fun MyCustomRow(
modifier: Modifier = Modifier,
items: List<String>,
) {
val childrenWidths = remember {
mutableStateListOf<Int>()
}
Box(
modifier = modifier
.background(Color.LightGray)
.height(IntrinsicSize.Min),
) {
// To add more box here
Box(
modifier = Modifier
.widthIn(
min = 64.dp,
)
.fillMaxHeight()
.width(childrenWidths.getOrNull(0)?.dp ?: 64.dp)
.background(
color = DarkGray,
),
)
Row(
horizontalArrangement = Arrangement.Center,
) {
items.mapIndexed { index, text ->
Text(
modifier = Modifier
.widthIn(min = 64.dp)
.padding(
vertical = 8.dp,
horizontal = 12.dp,
)
.onGloballyPositioned {
childrenWidths.add(index, it.size.width)
},
text = text,
color = Black,
textAlign = TextAlign.Center,
)
}
}
}
}
The size you get from Modifier.onSizeChanged or Modifier.onGloballyPositioned is in px with unit Int, not in dp. You should convert them to dp with
val density = LocalDensity.current
density.run{it.size.width.toDp()}
Full code
#Composable
fun MyCustomRow(
modifier: Modifier = Modifier,
items: List<String>,
) {
val childrenWidths = remember {
mutableStateListOf<Dp>()
}
Box(
modifier = modifier
.background(Color.LightGray)
.height(IntrinsicSize.Min),
) {
val density = LocalDensity.current
// To add more box here
Box(
modifier = Modifier
.widthIn(
min = 64.dp,
)
.fillMaxHeight()
.width(childrenWidths.getOrNull(0) ?: 64.dp)
.background(
color = DarkGray,
),
)
Row(
horizontalArrangement = Arrangement.Center,
) {
items.mapIndexed { index, text ->
Text(
modifier = Modifier
.onGloballyPositioned {
childrenWidths.add(index, density.run { it.size.width.toDp() })
}
.widthIn(min = 64.dp)
.padding(
vertical = 8.dp,
horizontal = 12.dp,
),
text = text,
color = Black,
textAlign = TextAlign.Center,
)
}
}
}
}
However this is not the optimal way to get size since it requires at least one more recomposition. Optimal way for getting size is using SubcomposeLayout as in this answer
How to get exact size without recomposition?
TabRow also uses SubcomposeLayout for getting indicator and divider widths
#Composable
fun TabRow(
selectedTabIndex: Int,
modifier: Modifier = Modifier,
containerColor: Color = TabRowDefaults.containerColor,
contentColor: Color = TabRowDefaults.contentColor,
indicator: #Composable (tabPositions: List<TabPosition>) -> Unit = #Composable { tabPositions ->
TabRowDefaults.Indicator(
Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex])
)
},
divider: #Composable () -> Unit = #Composable {
Divider()
},
tabs: #Composable () -> Unit
) {
Surface(
modifier = modifier.selectableGroup(),
color = containerColor,
contentColor = contentColor
) {
SubcomposeLayout(Modifier.fillMaxWidth()) { constraints ->
val tabRowWidth = constraints.maxWidth
val tabMeasurables = subcompose(TabSlots.Tabs, tabs)
val tabCount = tabMeasurables.size
val tabWidth = (tabRowWidth / tabCount)
val tabRowHeight = tabMeasurables.fold(initial = 0) { max, curr ->
maxOf(curr.maxIntrinsicHeight(tabWidth), max)
}
val tabPlaceables = tabMeasurables.map {
it.measure(
constraints.copy(
minWidth = tabWidth,
maxWidth = tabWidth,
minHeight = tabRowHeight
)
)
}
val tabPositions = List(tabCount) { index ->
TabPosition(tabWidth.toDp() * index, tabWidth.toDp())
}
layout(tabRowWidth, tabRowHeight) {
tabPlaceables.forEachIndexed { index, placeable ->
placeable.placeRelative(index * tabWidth, 0)
}
subcompose(TabSlots.Divider, divider).forEach {
val placeable = it.measure(constraints.copy(minHeight = 0))
placeable.placeRelative(0, tabRowHeight - placeable.height)
}
subcompose(TabSlots.Indicator) {
indicator(tabPositions)
}.forEach {
it.measure(Constraints.fixed(tabRowWidth, tabRowHeight)).placeRelative(0, 0)
}
}
}
}
}

step progress bar with android compose

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

Categories

Resources