Using Button, I want to make its diminensions such that its border hugs its width, with a minimum width and height of 40dp. In the sample below, I like the looks of the BigNumber preview. It does not have any outside horizontal padding. The Default preview does have padding outside the border. How do I fix this without setting an absolute width? Consider this sample:
#Composable
fun BasketQuantityStepper(
quantityControlsViewState: QuantityControlsViewState,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Button(
onClick = onClick,
colors = ButtonDefaults.buttonColors(backgroundColor = colorResource(id = R.color.basketQuantityStepperBackground)),
border = BorderStroke(dimensionResource(id = R.dimen.buttonBorderWidth), colorResource(id = R.color.basketQuantityStepperBorderColor)),
modifier = modifier
.heightIn(min = 40.dp)
.widthIn(min = 40.dp),
) {
Text(
text = "${quantityControlsViewState.currentQuantity}",
)
}
}
#Preview
#Composable
private fun PreviewDefault() {
BasketQuantityStepper(quantityControlsViewState = QuantityControlsViewState(
currentQuantity = 1,
minOrderQuantity = 1,
maxOrderQuantity = 10,
stepQuantity = 1
), onClick = {})
}
#Preview
#Composable
private fun PreviewBigNumber() {
BasketQuantityStepper(quantityControlsViewState = QuantityControlsViewState(
currentQuantity = 100,
minOrderQuantity = 1,
maxOrderQuantity = 1000,
stepQuantity = 1
), onClick = {})
}
Minimum dimension of Composables' touch area is 48.dp by default for accessibility.
You can remove it by wrapping your button with
CompositionLocalProvider(LocalMinimumTouchTargetEnforcement provides false) {
}
but it's not advised to have Composable's smaller than accebility size. Icons, CheckBox, even Slider uses 48.dp by default.
CompositionLocalProvider(LocalMinimumTouchTargetEnforcement provides false) {
Button(
onClick = {},
border = BorderStroke(2.dp, Color.LightGray),
modifier = Modifier
.border(2.dp, Color.Green)
.heightIn(min = 40.dp)
.widthIn(min = 40.dp),
) {
Text(
text = "$counter",
)
}
}
https://developer.android.com/jetpack/compose/accessibility
Remove Default padding around checkboxes in Jetpack Compose new update
Related
I am trying to create multiple items to encapsulate the specific behavior of every component but I cannot specify the dimensions for every view.
I want a Textfield with an X icon on its right
setContent {
Surface(
modifier = Modifier
.fillMaxSize()
.background(color = white)
.padding(horizontal = 15.dp)
) {
Row(horizontalArrangement = Arrangement.spacedBy(15.dp)) {
Searcher(
modifier = Modifier.weight(1f),
onTextChanged = { },
onSearchAction = { }
)
Image(
painter = painterResource(id = R.drawable.ic_close),
contentDescription = null,
colorFilter = ColorFilter.tint(blue)
)
}
}
}
The component is the following
#Composable
fun Searcher(
modifier: Modifier = Modifier,
onTextChanged: (String) -> Unit,
onSearchAction: () -> Unit
) {
Row {
SearcherField(
onTextChanged = onTextChanged,
onSearchAction = onSearchAction,
modifier = Modifier.weight(1f)
)
CircularSearch(
modifier = Modifier
.padding(horizontal = 10.dp)
.align(CenterVertically)
)
}
}
and the SearcherField:
#Composable
fun SearcherField(
modifier: Modifier = Modifier,
onTextChanged: (String) -> Unit,
onSearchAction: () -> Unit
) {
var fieldText by remember { mutableStateOf(emptyText) }
TextField(
value = fieldText,
onValueChange = { value ->
fieldText = value
if (value.length > 2)
onTextChanged(value)
},
singleLine = true,
textStyle = Typography.h5.copy(color = White),
colors = TextFieldDefaults.textFieldColors(
cursorColor = White,
focusedIndicatorColor = Transparent,
unfocusedIndicatorColor = Transparent,
backgroundColor = Transparent
),
trailingIcon = {
if (fieldText.isNotEmpty()) {
IconButton(onClick = {
fieldText = emptyText
}) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = emptyText
)
}
}
},
placeholder = {
Text(
text = stringResource(id = R.string.dondebuscas),
style = Typography.h5.copy(color = White)
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(
onSearch = {
onSearchAction()
}
),
modifier = modifier.fillMaxWidth()
)
}
But I don´t know why, but the component Searcher with the placeholder is rendered in two lines.
It´s all about the placeholder that seems to be resized for not having enough space because if I remove the placeholder, the component looks perfect.
Everything is in one line, not having a placeholder of two lines. I m trying to modify the size of every item but I am not able to get the expected result and I don´t know if the problem is just about the placeholder.
How can I solve it? UPDATE -> I found the error
Thanks in advance!
Add maxlines = 1 to the placeholder Text's parameters.
Your field is single -lune but your text is multi-line. I think it creates conflict in implementation.
Okay... I find that the problem is about the trailing icon. Is not visible when there is no text in the TextField but is still occupying some space in the view, that´s why the placeholder cannot occupy the entire space. The solution is the following.
val trailingIconView = #Composable {
IconButton(onClick = {
fieldText = emptyText
}) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = emptyText
)
}
}
Create a variable with the icon and set it to the TextField only when is required
trailingIcon = if (fieldText.isNotEmpty()) trailingIconView else null,
With that, the trailing icon will be "gone" instead of "invisible" (the old way).
Still have a lot to learn.
I am trying the change a button background from a solid color to a dawable image with transparent background to make sure I can see the pattern
I moved to jetpack so I have created
Button(onClick = { /*TODO*/ },
colors = ButtonDefaults.buttonColors(
backgroundColor = colorResource(id = R.color.gainsboro_00)),
modifier = Modifier
.fillMaxWidth()
.height(60.dp),
shape = RoundedCornerShape(0.dp)) {
Text(text = stringResource(id = R.string.login),
color = colorResource(id = R.color.gainsboro_05),
style = MaterialTheme.typography.body1)
}
This button has a grey background.
I would like to apply the drawable below:
<?xml version="1.0" encoding="UTF-8" ?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="#drawable/pattern_stripe_loose_gainsboro_05"
android:tileMode="repeat"/>
as a background instead of the colored one and have the pattern displayed. the above xml is just repeating a pattern to create a background
So I expect this:
using the pattern:
When using the traditional way with layout and so on it works but I can't make it work on jetpack
Any idea ?
Compose does not have such a feature yet. You can create a feature request on issue tracker.
Before this is implemented, you could create a pure Compose solution that draws a lot of images, but I think there is no point in doing that when there is ImageView already optimized by engineers. In such cases you can use AndroidView for interop with old views.
#Composable
fun TileAndroidImage(
#DrawableRes drawableId: Int,
contentDescription: String,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val drawable = remember(drawableId) {
BitmapDrawable(
context.resources,
BitmapFactory.decodeResource(
context.resources,
drawableId
)
).apply {
tileModeX = Shader.TileMode.REPEAT
tileModeY = Shader.TileMode.REPEAT
}
}
AndroidView(
factory = {
ImageView(it)
},
update = { imageView ->
imageView.background = drawable
},
modifier = modifier
.semantics {
this.contentDescription = contentDescription
role = Role.Image
}
)
}
Next part, is puttin it in background of the button. In compose we use containers to do so. You can create your TiledButton. I pass zero padding to container button and add real padding manually so it'll not affect the background:
#Composable
fun TiledButton(
onClick: () -> Unit,
#DrawableRes backgroundDrawableId: Int,
modifier: Modifier = Modifier,
enabled: Boolean = true,
shape: Shape = MaterialTheme.shapes.small,
border: BorderStroke? = null,
contentColor: Color = MaterialTheme.colors.primary,
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
content: #Composable RowScope.() -> Unit
) {
Button(
onClick = onClick,
contentPadding = PaddingValues(0.dp),
enabled = enabled,
shape = shape,
border = border,
elevation = null,
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Transparent,
contentColor = contentColor,
disabledBackgroundColor = Color.Transparent,
disabledContentColor = contentColor.copy(alpha = ContentAlpha.disabled),
),
modifier = modifier
) {
Box(
contentAlignment = Alignment.Center,
) {
TileAndroidImage(
drawableId = backgroundDrawableId,
contentDescription = "...",
modifier = Modifier.matchParentSize()
)
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(contentPadding),
content = content,
)
}
}
}
Usage:
TiledButton(
onClick = { /*TODO*/ },
backgroundDrawableId = R.drawable.tile,
border = BorderStroke(1.dp, Color.Blue),
) {
Text("Apple")
}
Why not just create a box with that background and place a text while making the entire box clickable? The box will act as the entire button. I mean that's what a button essentially is, isn't it? A box containing some text? Oh, if you cannot figure out a way to get the drawable set as a background on your Box, just use something like an Image combined with the fillMaxSize() Modifier.
Something like
Box(Modifier.fillMaxWidth().height(...),
horizontalArrangement = Arrangement.CenterHorizontally){
Image(painter = painterResource(R.drawable.b_pattern),
contentDescription = "Lorem Ipsum")
Text(modifier = Modifier.align(Alignment.CenterVertically),
text = "Lorem Ipsum")
}
Just try it out and let me know please.
I am trying to remove padding from TextButton but it wont work.
TextButton(
onClick = {},
modifier = Modifier.padding(0.dp)
) {
Text(
" ${getString(R.string.terms_and_conditions)}",
color = MaterialTheme.colors.primary,
fontFamily = FontFamily(Font(R.font.poppins_regular)),
fontSize = 10.sp,
)
}
I have tried setting the height and size in Modifier property as well but the padding is still present
Wrap the TextButton with CompositionLocalProvider to override the value of LocalMinimumTouchTargetEnforcement. This will only remove the extra margin but will not modify the defaultMinSize which is hardcoded.
CompositionLocalProvider(
LocalMinimumTouchTargetEnforcement provides false,
) {
TextButton(
onClick = {},
contentPadding = PaddingValues(),
) {
Text(
"Button",
color = MaterialTheme.colors.primary,
fontSize = 10.sp,
)
}
}
You cannot reduce padding with the padding modifier: it always adds an extra padding on top of the existing padding. See this reply for more details about the order of modifiers.
You can reduce TextButton padding with contentPadding argument, by specifying PaddingValues(0.dp), but this will not fully remove the padding.
If you need fully remove the padding, you can use the clickable modifier instead:
Text(
"getString(R.string.terms_and_conditions",
color = MaterialTheme.colors.primary,
fontFamily = FontFamily(Font(R.font.neris_semi_bold)),
fontSize = 10.sp,
modifier = Modifier
.clickable {
// onClick()
}
)
If you want to change the color of the ripple, as is done in TextButton, you can do it as follows:
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(color = MaterialTheme.colors.primary),
) {
}
You can achieve it changing the contentPadding and applying a fixed size:
TextButton(
onClick = {},
contentPadding = PaddingValues(0.dp),
modifier = Modifier.height(20.dp).width(40.dp)
) {
Text(
"Button",
color = MaterialTheme.colors.primary,
fontSize = 10.sp,
)
}
If you come across unwanted margins. When you use onclick in any Button function, it sets propagateMinConstraints = true inside the view's surface - this will apply to unwanted margins. Example how solve this problem:
#Composable
fun ButtonWithoutOuterPadding(
onClick: () -> Unit,
modifier: Modifier = Modifier,
shape: Shape = RectangleShape,
elevation: Dp = 0.dp,
color: Color = Color.Transparent,
border: BorderStroke? = null,
contentAlignment: Alignment = Alignment.Center,
content: #Composable () -> Unit
) {
Box(
modifier
.shadow(elevation, shape, clip = false)
.then(if (border != null) Modifier.border(border, shape) else Modifier)
.background(
color = color,
shape = shape
)
.clip(shape)
.then(
Modifier.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = LocalIndication.current,
enabled = true,
onClickLabel = null,
role = null,
onClick = onClick
)
),
contentAlignment = contentAlignment,
propagateMinConstraints = false
) {
content()
}
}
When using ConstraintLayout in a LazyColumn a simple Text does not appear when we simply scroll up and down.
Changing the Item from a ConstraintLayout to a Row fixes the issue thus I conclude either my code is bugged or ConstraintLayout alpha has a bug.
You can see in the Layout inspector picture the Text is supposed to display a -6.40 euro
edit: I also posted it on the android bug tracker as I wasn't sure if it was my problem or a bug https://issuetracker.google.com/issues/188855913 - Will close this soon most probably
LazyColumn(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(smallMargin),
) {
item {
header()
}
transactionsGroupedPer.forEach { (section, transactions) ->
item {
Text(
modifier = modifier.padding(start = largeMargin, end = largeMargin, top = normalMargin),
text = section.uppercase(),
style = MyTheme.typography.label
)
}
items(items) {
MyItem(
item = it,
modifier = Modifier.fillParentMaxWidth(),
)
}
}
}
#Composable
fun MyItem(
name: String,
amount: Money,
modifier: Modifier = Modifier,
textColor: Color = Color.Unspecified,
) {
val constraints = ConstraintSet {
val titleSubTitle = createRefFor(ModifierId.TITLE_SUBTITLE)
val logo = createRefFor(ModifierId.LOGO)
val amount = createRefFor(ModifierId.AMOUNT)
constrain(amount) {
top.linkTo(parent.top, margin = xsmallMargin)
bottom.linkTo(parent.bottom, margin = xsmallMargin)
end.linkTo(parent.end, margin = smallMargin)
}
constrain(logo) {
start.linkTo(parent.start, margin = smallMargin)
bottom.linkTo(parent.bottom)
}
constrain(titleSubTitle) {
top.linkTo(logo.top)
bottom.linkTo(logo.bottom)
start.linkTo(logo.end, margin = smallMargin)
end.linkTo(amount.start, margin = smallMargin)
width = Dimension.fillToConstraints
}
}
ConstraintLayout(constraints,
modifier = modifier.fillMaxWidth().wrapContentHeight()
) {
Text(
color = textColor,
modifier = Modifier.layoutId(ModifierId.AMOUNT),
text = amount.toMoneyAnnotatedString(),
style = amountStyle,
)
ImageContainer(Modifier.layoutId(ModifierId.LOGO), image = image, size = logoSize)
Column(modifier = Modifier.layoutId(ModifierId.TITLE_SUBTITLE), verticalArrangement = Arrangement.Center) {
Text(
color = textColor,
maxLines = maxLines,
text = name,
style = MyTheme.typography.bodyBold
)
if (showSubTitle) {
Text(
color = textColor,
text = date.formatDateTime(DateFormat.LONG),
style = MyTheme.typography.meta
)
}
}
}
}
Bug fixed in beta08
References
https://issuetracker.google.com/issues/188855913
https://issuetracker.google.com/issues/188566058
I need to implement LazyColumn with top fading edge effect. On Android I use fade gradient for ListView or RecyclerView, but couldn't find any solution for Jetpack Compose!
I tried to modify canvas:
#Composable
fun Screen() {
Box(
Modifier
.fillMaxWidth()
.background(color = Color.Yellow)
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.drawWithContent {
val colors = listOf(Color.Transparent, Color.Black)
drawContent()
drawRect(
brush = Brush.verticalGradient(colors),
blendMode = BlendMode.DstIn
)
}
) {
itemsIndexed((1..1000).toList()) { item, index ->
Text(
text = "Item $item: $index value",
modifier = Modifier.padding(12.dp),
color = Color.Red,
fontSize = 24.sp
)
}
}
}
}
But have wrong result:
What you could do is place a Spacer on top of the list, and draw a gradient on that Box. Make the Box small so only a small portion of the list has the overlay. Make the color the same as the background of the screen, and it will look like the content is fading.
val screenBackgroundColor = MaterialTheme.colors.background
Box(Modifier.fillMaxSize()) {
LazyColumn(Modifier.fillMaxSize()) {
//your items
}
//Gradient overlay
Spacer(
Modifier
.fillMaxWidth()
.height(32.dp)
.background(
brush = Brush.verticalGradient(
colors = listOf(
Color.Transparent,
screenBackgroundColor
)
)
)
//.align(Alignment) to control the position of the overlay
)
}
Here's how it would look like:
However, this doesn't seem like quite what you asked for since it seems like you want the actual list content to fade out.
I don't know how you would apply an alpha to only a portion of a view. Perhaps try to dig into the .alpha sources to figure out.
Quick hack which fixes the issue: add .graphicsLayer { alpha = 0.99f } to your modifer
By default Jetpack Compose disables alpha compositing for performance reasons (as explained here; see the "Custom Modifier" section). Without alpha compositing, blend modes which affect transparency (e.g. DstIn) don't have the desired effect. Currently the best workaround is to add .graphicsLayer { alpha = 0.99F } to the modifier on the LazyColumn; this forces Jetpack Compose to enable alpha compositing by making the LazyColumn imperceptibly transparent.
With this change, your code looks like this:
#Composable
fun Screen() {
Box(
Modifier
.fillMaxWidth()
.background(color = Color.Yellow)
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
// Workaround to enable alpha compositing
.graphicsLayer { alpha = 0.99F }
.drawWithContent {
val colors = listOf(Color.Transparent, Color.Black)
drawContent()
drawRect(
brush = Brush.verticalGradient(colors),
blendMode = BlendMode.DstIn
)
}
) {
itemsIndexed((1..1000).toList()) { item, index ->
Text(
text = "Item $item: $index value",
modifier = Modifier.padding(12.dp),
color = Color.Red,
fontSize = 24.sp
)
}
}
}
}
which produces the correct result
Just a little nudge in the right direction. What this piece of code does is place a Box composable at the top of your LazyColumn with an alpha modifier for fading. You can make multiple of these Box composables in a Column again to create a smoother effect.
#Composable
fun FadingExample() {
Box(
Modifier
.fillMaxWidth()
.requiredHeight(500.dp)) {
LazyColumn(Modifier.fillMaxSize()) {
}
Box(
Modifier
.fillMaxWidth()
.height(10.dp)
.alpha(0.5f)
.background(Color.Transparent)
.align(Alignment.TopCenter)
) {
}
}
}
I optimised the #user3872620 solution. You have just to put this lines below your LazyColumn, VerticalPager.. and just adapt your offset / height, usually offset = height
Box(
Modifier
.fillMaxWidth()
.offset(y= (-10).dp)
.height(10.dp)
.background(brush = Brush.verticalGradient(
colors = listOf(
Color.Transparent,
MaterialTheme.colors.background
)
))
)
You will got this render:
There is the render
This is a very simple implementation of FadingEdgeLazyColumn using AndroidView. Place AndroidView with gradient background applied to the top and bottom of LazyColumn.
#Stable
object GradientDefaults {
#Stable
val Color = androidx.compose.ui.graphics.Color.Black
#Stable
val Height = 30.dp
}
#Stable
sealed class Gradient {
#Immutable
data class Top(
val color: Color = GradientDefaults.Color,
val height: Dp = GradientDefaults.Height,
) : Gradient()
#Immutable
data class Bottom(
val color: Color = GradientDefaults.Color,
val height: Dp = GradientDefaults.Height,
) : Gradient()
}
#Composable
fun FadingEdgeLazyColumn(
modifier: Modifier = Modifier,
gradients: Set<Gradient> = setOf(Gradient.Top(), Gradient.Bottom()),
contentGap: Dp = 0.dp,
state: LazyListState = rememberLazyListState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
userScrollEnabled: Boolean = true,
content: LazyListScope.() -> Unit,
) {
val topGradient =
remember(gradients) { gradients.find { it is Gradient.Top } as? Gradient.Top }
val bottomGradient =
remember(gradients) { gradients.find { it is Gradient.Bottom } as? Gradient.Bottom }
ConstraintLayout(modifier = modifier) {
val (topGradientRef, lazyColumnRef, bottomGradientRef) = createRefs()
GradientView(
modifier = Modifier
.constrainAs(topGradientRef) {
top.linkTo(parent.top)
width = Dimension.matchParent
height = Dimension.value(topGradient?.height ?: GradientDefaults.Height)
}
.zIndex(2f),
colors = intArrayOf(
(topGradient?.color ?: GradientDefaults.Color).toArgb(),
Color.Transparent.toArgb()
),
visible = topGradient != null
)
LazyColumn(
modifier = Modifier
.constrainAs(lazyColumnRef) {
top.linkTo(
anchor = topGradientRef.top,
margin = when (topGradient != null) {
true -> contentGap
else -> 0.dp
}
)
bottom.linkTo(
anchor = bottomGradientRef.bottom,
margin = when (bottomGradient != null) {
true -> contentGap
else -> 0.dp
}
)
width = Dimension.matchParent
height = Dimension.fillToConstraints
}
.zIndex(1f),
state = state,
contentPadding = contentPadding,
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled,
content = content
)
GradientView(
modifier = Modifier
.constrainAs(bottomGradientRef) {
bottom.linkTo(parent.bottom)
width = Dimension.matchParent
height = Dimension.value(bottomGradient?.height ?: GradientDefaults.Height)
}
.zIndex(2f),
colors = intArrayOf(
Color.Transparent.toArgb(),
(bottomGradient?.color ?: GradientDefaults.Color).toArgb(),
),
visible = bottomGradient != null
)
}
}
#Composable
private fun GradientView(
modifier: Modifier = Modifier,
#Size(value = 2) colors: IntArray,
visible: Boolean = true,
) {
AndroidView(
modifier = modifier,
factory = { context ->
val gradientBackground = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
colors
).apply {
cornerRadius = 0f
}
View(context).apply {
layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT
)
background = gradientBackground
visibility = when (visible) {
true -> View.VISIBLE
else -> View.INVISIBLE
}
}
}
)
}