Compose widgets conflicting scroll - android

I have vertical pager and text composable that expands by click and scrollable modifier when expanded, text is located at bottom of screen and sometimes conflicts with pager scroll
How can i fix that? I tried to enable scroll only when text overlaps but this didn't work in my case
So question is how to enable scroll only when text is overflow ?
this is my description widget
#Composable
private fun ExpandableDescription(
modifier: Modifier = Modifier,
isExpanded: Boolean,
description: String,
prices: AnnotatedString,
onClick: () -> Unit,
) {
val isScrollEnabled = remember(isExpanded) { mutableStateOf(false) }
val scrollModifier =
Modifier.verticalScroll(rememberScrollState(), enabled = isScrollEnabled.value)
Box(
modifier = Modifier
.animateContentSize()
.then(modifier)
.then(scrollModifier)
.clickable { onClick() }
) {
Column {
Text(
text = description + description + description + description + description,
color = CryptoTheme.colors.primaryText,
fontSize = 14.sp,
onTextLayout = {
Timber.v("hasVisual=${it.hasVisualOverflow}")
isScrollEnabled.value = it.hasVisualOverflow
}
)
Text(modifier = Modifier.padding(top = 10.dp),
text = prices,
lineHeight = 28.sp,
onTextLayout = {
Timber.v("hasVisual2=${it.hasVisualOverflow}")
isScrollEnabled.value = it.hasVisualOverflow
}
)
}
TransparentField(
Modifier
.align(Alignment.BottomCenter)
.alpha(if (isExpanded) 0f else 1f)
)
}
}

Related

Align row item in jetpack compose

I want to make row like this
Expected Output
AND
I tried this piece of code
DividerWithItem
#Composable
fun DividerWithItem(
modifier: Modifier = Modifier,
index: () -> Int,
itemName: String,
lastIndex: () -> Int,
moreRowContent: #Composable RowScope.() -> Unit,
) {
Column {
if (index() == 0) {
Divider(color = Cloudy, thickness = dimensionResource(R.dimen.separator_height_width))
}
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = itemName,
modifier = Modifier.padding(vertical = 12.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
moreRowContent()
}
if (index() <= lastIndex()) {
Divider(color = Cloudy, thickness = 1.dp)
}
}
}
BpmOptionsLabel
#OptIn(ExperimentalFoundationApi::class)
#Composable
fun LazyItemScope.BpmOptionsLabel(
index: () -> Int,
optionName: String,
lastIndex: () -> Int
) {
DividerWithItem(
modifier = Modifier
.fillMaxSize()
.animateItemPlacement(),
index = index,
itemName = optionName,
lastIndex = lastIndex
) {
Image(
modifier = Modifier.weight(.3f),
painter = painterResource(R.drawable.ic_menu),
contentDescription = null,
)
}
}
BpmOptionsLabelPreview
#Preview(showBackground = true)
#Composable
fun BpmOptionsLabelPreview() {
LazyColumn {
item {
BpmOptionsLabel(
index = { 0 },
"Item item item item item m 1",
lastIndex = { 1 }
)
}
}
}
Actual Output
Only problem is Text and Image item is not in proper place
In the DividerWithItem apply the weight(1f) to the Text
Text(
text = itemName,
modifier = Modifier.padding(vertical = 12.dp).weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
moreRowContent()
and in the LazyItemScope.BpmOptionsLabel remove the weight modifier from the Image:
Image(
//modifier = Modifier.weight(.3f),
painter = painterResource(R.drawable.ic_menu_gallery),
contentDescription = null
)
If you want to increase the space occupied by the Image, use a padding modifier:
Image(
//...
modifier = Modifier.padding(horizontal = 20.dp)
)
You can try this, just add weight to your text, and the image will follow the remaining size that it needs depending on its size.
#Preview(showBackground = true)
#Composable
fun TextOverflow(){
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
modifier = Modifier.weight(1f),
text = "This is should be long-long text that ever you see today, I even don't know how far this text will be ended, so just enjoy reading while you code.",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Icon(imageVector = Icons.Rounded.MoreHoriz, contentDescription = "")
}
}
The Result:

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 wrapContentHeight/ heightIn is adding aditional space around the buttons

I am learning Jetpack Compose, and I've created a few set of buttons as a practice.
This is the button
#Composable
fun MyButton(
text: String,
modifier: Modifier = Modifier,
isEnabled: Boolean = true,
onClick: () -> Unit,
) {
Button(
enabled = isEnabled,
onClick = { onClick() },
modifier = modifier.width(270.dp).wrapContentHeight(),
) {
Text(
text = text,
style = MaterialTheme.typography.button
)
}
}
The problem is, that if i set the height of the button to wrapContentHeight or use heightIn with different max and min values, compose automatically adds a space around the button as seen here
But if i remove WrapContent, and use a fixed height, or define same min and max height for heightIn this probblem does not appear
#Composable
fun MyButton(
text: String,
modifier: Modifier = Modifier,
isEnabled: Boolean = true,
onClick: () -> Unit,
) {
Button(
enabled = isEnabled,
onClick = { onClick() },
modifier = modifier.width(270.dp).height(36.dp),
) {
Text(
text = text,
style = MaterialTheme.typography.button
)
}
}
And this is the code used for the column/preview of the functions:
#Composable
private fun SampleScreen() {
MyTheme{
Surface(modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background,){
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp, Alignment.CenterVertically),
modifier = Modifier.padding(20.dp)
) {
var isEnabled by remember { mutableStateOf(false) }
MyButton("Enable/Disable") {
isEnabled = !isEnabled
}
MyButton("Button") {}
MyButton(text = "Disabled Button", isEnabled = isEnabled) {}
}
}
}
}
Even if I remove the spacedBy operator from column the same issue appears.
I have tried to search for an explanation to this, but I did not manage to find anything.
Any help or resource with explanations is appreciated.
This is because Minimum dimension of Composables touch area is 48.dp by default for accessibility. However you can override this by using
CompositionLocalProvider(LocalMinimumTouchTargetEnforcement provides false) {
Button(
enabled = isEnabled,
onClick = { onClick() },
modifier = modifier.heightIn(min = 20.dp)
.widthIn(min = 20.dp),
) {
Text(
text = text,
style = MaterialTheme.typography.button
)
}
}
Or something like
Button(modifier = Modifier.absoluteOffset((-12).dp, 0.dp)){
Text(
text = text,
style = MaterialTheme.typography.button
)
}

Make LazyColumn items be as large as the largest item in the list

#Composable
fun PreviewLayout() {
fun getRandomString(length: Int): String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
val horizontalScrollState = rememberScrollState()
LazyColumn(
modifier = Modifier
.background(Color.Blue)
.fillMaxHeight()
.wrapContentWidth()
.horizontalScroll(horizontalScrollState)
) {
items(5) { index ->
Text(
text = getRandomString((index + 1) * 4).uppercase(),
color = Color.Black,
fontSize = 16.sp,
modifier = Modifier
.padding(8.dp)
.background(Color.Yellow)
)
}
}
}
Preview of the layout:
I'd like to have the items width be the same as the largest item in the list.
Notice the .horizontalScroll(horizontalScrollState), this is to allow horizontal scrolling.
What I'd like:
I need to use a LazyColumn but if I could use a Column I'd write it this way:
Column(
modifier = Modifier
.background(Color.Blue)
.horizontalScroll(horizontalScrollState)
.fillMaxHeight()
.width(IntrinsicSize.Min)
) {
repeat(5) { index ->
Text(
text = getRandomString((index + 1) * 4).uppercase(),
color = Color.Black,
fontSize = 16.sp,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.background(Color.Yellow)
)
}
}
You need to calculate width of the widest element separately. You can do it by placing an invisible copy of you cell with widest content in a Box along with LazyColumn.
In your sample it's easy - just get the longest string. If in the real project you can't decide which of contents is gonna be the widest one, you have two options:
1.1. Place all of them one on top of each other. You can do it only if you have some limited number of cells,
1.2. Otherwise you have to made some approximation and filter a short list of the ones you expect to be the widest ones.
Because of horizontalScroll maxWidth constraint is infinity, you have to pass calculated width manually. You can get it with onSizeChanged:
#Composable
fun TestScreen(
) {
fun getRandomString(length: Int): String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
val items = remember {
List(30) { index ->
getRandomString((index + 1) * 4).uppercase()
}
}
val maxLengthItem = remember(items) {
items.maxByOrNull { it.length }
}
val (maxLengthItemWidthDp, setMaxLengthItemWidthDp) = remember {
mutableStateOf<Dp?>(null)
}
val horizontalScrollState = rememberScrollState()
Box(
Modifier
.background(Color.Blue)
.horizontalScroll(horizontalScrollState)
) {
LazyColumn(
Modifier.fillMaxWidth()
) {
items(items) { item ->
Cell(
item,
modifier = if (maxLengthItemWidthDp != null) {
Modifier.width(maxLengthItemWidthDp)
} else {
Modifier
}
)
}
}
if (maxLengthItem != null) {
val density = LocalDensity.current
Cell(
maxLengthItem,
modifier = Modifier
.requiredWidthIn(max = Dp.Infinity)
.onSizeChanged {
setMaxLengthItemWidthDp(with(density) { it.width.toDp() })
}
.alpha(0f)
)
}
}
}
#Composable
fun Cell(
item: String,
modifier: Modifier,
) {
Text(
text = item,
color = Color.Black,
fontSize = 16.sp,
modifier = modifier
.padding(8.dp)
.background(Color.Yellow)
)
}
Result:
This is not possible when horizontal srolling is enabled.
Regular Modifier.fillMaxWidth can't work inside the scrolling
horizontally layouts as the items are measured with
Constraints.Infinity as the constraints for the main axis.
If you want your Column solution to work, you need to place it inside another contain (like a Box) and apply horizontal scrolling to the parent. Scrolling on the Column itself needs to be removed:
Box(
modifier = Modifier
.requiredWidth(250.dp)
.fillMaxHeight()
.horizontalScroll(rememberScrollState())
) {
Column(
modifier = Modifier
.background(Color.Blue)
.fillMaxHeight()
.width(IntrinsicSize.Min)
) {
repeat(5) { index ->
Text(
text = getRandomString((index + 1) * 40).uppercase(),
color = Color.Black,
fontSize = 16.sp,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.background(Color.Yellow)
)
}
}
}
#Composable
fun PreviewLayout() {
fun getRandomString(length: Int): String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
val horizontalScrollState = rememberScrollState()
LazyColumn(
modifier = Modifier
.background(Color.Blue)
.fillMaxHeight()
.horizontalScroll(horizontalScrollState)
) {
items(5) { index ->
Text(
text = getRandomString((index + 1) * 4).uppercase(),
color = Color.Black,
fontSize = 16.sp,
modifier = Modifier
.padding(8.dp)
.width(width = 200.dp)
.background(Color.Yellow)
)
}
}
}

Jetpack Compose onClick ripple is not propagating with a circular motion?

As can be seen in gif
when Column that contains of Text, Spacer, and LazyRowForIndexed is touched ripple is not propagating with circular motion. And it gets touched effect even when horizontal list is touched.
#Composable
fun Chip(modifier: Modifier = Modifier, text: String) {
Card(
modifier = modifier,
border = BorderStroke(color = Color.Black, width = Dp.Hairline),
shape = RoundedCornerShape(8.dp)
) {
Row(
modifier = Modifier.padding(start = 8.dp, top = 4.dp, end = 8.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier.preferredSize(16.dp, 16.dp)
.background(color = MaterialTheme.colors.secondary)
)
Spacer(Modifier.preferredWidth(4.dp))
Text(text = text)
}
}
}
#Composable
fun TutorialSectionCard(model: TutorialSectionModel) {
Column(
modifier = Modifier
.padding(top = 8.dp)
.clickable(onClick = { /* Ignoring onClick */ })
.padding(16.dp)
) {
Text(text = model.title, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.h6)
Spacer(Modifier.preferredHeight(8.dp))
Providers(AmbientContentAlpha provides ContentAlpha.medium) {
Text(model.description, style = MaterialTheme.typography.body2)
}
Spacer(Modifier.preferredHeight(16.dp))
LazyRowForIndexed(items = model.tags) { _: Int, item: String ->
Chip(text = item)
Spacer(Modifier.preferredWidth(4.dp))
}
}
}
#Preview
#Composable
fun TutorialSectionCardPreview() {
val model = TutorialSectionModel(
clazz = MainActivity::class.java,
title = "1-1 Column/Row Basics",
description = "Create Rows and Columns that adds elements in vertical order",
tags = listOf("Jetpack", "Compose", "Rows", "Columns", "Layouts", "Text", "Modifier")
)
Column {
TutorialSectionCard(model)
TutorialSectionCard(model)
TutorialSectionCard(model)
}
}
What should be done to have circular effect, but not when list itself or an item from list is touched, or scrolled?
You have to apply a Theme to your composable, which in turn provides a default ripple factory, or you have to set the ripple explicitly:
#Preview
#Composable
fun TutorialSectionCardPreview() {
MaterialTheme() {
Column {
TutorialSectionCard
...
}
}
}
or
Column(
modifier = Modifier
.padding(top = 8.dp)
.clickable(
onClick = { /* Ignoring onClick */ },
indication = rememberRipple(bounded = true)
)
.padding(16.dp)
) {
// content
}
(As of compose version 1.0.0-alpha09 there seems to be no way to prevent the ripple from showing when content is scrolled)
I'm using this approach:
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(
color = Color.Black
),
onClick = {
}
)
I also figured out how to keep ripple only for the card not the scrollable list that contains tags. To prevent ripple only move through cards use a Box which places it's children as a stack, and add clickable to section that contains header and text.
#Composable
fun TutorialSectionCard(
model: TutorialSectionModel,
onClick: ((TutorialSectionModel) -> Unit)? = null
) {
Card(
modifier = Modifier.padding(vertical = 3.dp, horizontal = 8.dp),
elevation = 1.dp,
shape = RoundedCornerShape(8.dp)
) {
Box(
contentAlignment = Alignment.BottomStart
) {
TutorialContentComponent(onClick, model)
TutorialTagsComponent(model)
}
}
}
#Composable
private fun TutorialContentComponent(
onClick: ((TutorialSectionModel) -> Unit)?,
model: TutorialSectionModel
) {
Column(Modifier
.clickable(
onClick = { onClick?.invoke(model) }
)
.padding(16.dp)
) {
Text(
text = model.title,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.h6
)
// Vertical spacing
Spacer(Modifier.height(8.dp))
// Description text
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(model.description, style = MaterialTheme.typography.body2)
}
// Vertical spacing
Spacer(Modifier.height(36.dp))
}
}
#Composable
private fun TutorialTagsComponent(model: TutorialSectionModel) {
Column(Modifier.padding(12.dp)) {
// Horizontal list for tags
LazyRow(content = {
items(model.tags) { tag ->
TutorialChip(text = tag)
Spacer(Modifier.width(8.dp))
}
})
}
}

Categories

Resources