I am creating a dropdown menu where the items contain a text element and an icon (a spacer in between); but only the first text is shown completely. The icon is only visible when there is another item taking more space.
#Preview(showSystemUi = true)
#Composable
fun MyScreen() {
Box(Modifier.fillMaxSize(), Alignment.Center) {
Box() {
var expanded by remember { mutableStateOf(false) }
IconButton(onClick = { expanded = !expanded }) {
Icon(imageVector = Icons.Default.MoreVert, contentDescription = null)
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
MyMenuItem("item 1") // Icon visible
MyMenuItem("item 2") // Icon visible
MyMenuItem("item 3 long text") // Icon width shrunk to 0
MyMenuItem("item 4 long te") // Icon visible but shrunk
}
}
}
}
#Composable
fun MyMenuItem(text: String) {
DropdownMenuItem(onClick = { }) {
Text(text)
Spacer(modifier = Modifier.weight(1f))
Icon(imageVector = Icons.Default.Check, contentDescription = null) // <-- Icon
}
}
Note :
I have also tried using Row() and Surface() in place of DropdownMenuItem() but the result is similar.
Giving width to the MyMenuItem() works; but I want it to size itself automatically based on content.
Generally speaking, to create such a layout you just need to apply Modifier.weight(1f) to your Text.
You also need Modifier.width(IntrinsicSize.Max) for your Column to make the width equal to the widest item, but in your case it's already built into DropdownMenu.
But then this bug pops up, which doesn't allow you to properly size your MyMenuItem with Icon inside. Please put a star to draw more attention to it.
As a temporary solution until this bug is fixed, you can specify the size of the icon manually, like this:
// copied from the source code as it's internal
const val MaterialIconDimension = 24f
#Composable
fun MyMenuItem(text: String) {
DropdownMenuItem(
onClick = { }
) {
Text(text, Modifier.weight(1f))
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
modifier = Modifier.size(MaterialIconDimension.dp)
)
}
}
Result:
Related
I'm trying to make a swipe to reveal component using compose, but I want the width of the card that will appear after the swipe to grow to the size of the wrap content without using it, but I don't understand how to calculate the wrap content size.
var width by remember {
mutableStateOf(0.dp)
}
val lowerTransition = updateTransition(transitionState, "lowerCardTransition")
val lowerOffsetTransition by lowerTransition.animateFloat(
label = "lowerCardOffsetTransition",
transitionSpec = { tween(durationMillis = ANIMATION_DURATION) },
targetValueByState = { if (isRevealed) width.value else 0f },
)
How do I equate the width value used here to the wrap content value?
I'm trying to make the resulting delete button appear all without using a constant value
Try using AnimatedVisibility. For demo purpose I used OnClick, replace it with OnSwipe.
#Preview
#Composable
fun AnimateVisibility2() {
var visible by remember {
mutableStateOf(false)
}
Row(
modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center
) {
AnimatedVisibility(
visible = visible, enter = expandHorizontally(), exit = shrinkHorizontally()
) {
IconButton(onClick = { /*TODO*/ }) {
Icon(Icons.Default.Phone, contentDescription = null)
}
}
Button(onClick = { visible = !visible }, Modifier.weight(1f)) {
Text("Click Me")
}
}
}
I'm using the new BackdropScaffold composable to make a similar looking screen like Google Map with a Map on the back and a list on the front. (See the image)
As you can see there is a problem with the corner around the front layer. Currently is displayed the surface under (pale blue). What I would like to achieve is having the Google Map shown in those corners. I tried to play with the size and padding of GoogleMap composable or the front panel but no luck.
UPDATE
The following example code shows the issue I'm facing. As you can see the BackdropScaffold background is correctly applied (RED). The corners of the front layer are transparent. The issue comes out when you have a different color in your background layer (BLUE). If the background layer contains a map you have the same issue.
BackdropScaffold is dividing the space but not overlaying any layer. The front layer should overlay a bit the back layer to fix this problem.
#OptIn(ExperimentalMaterialApi::class)
#Composable
internal fun test() {
val scope = rememberCoroutineScope()
val selection = remember { mutableStateOf(1) }
val scaffoldState = rememberBackdropScaffoldState(BackdropValue.Concealed)
val frontLayerHeightDp = LocalConfiguration.current.screenHeightDp / 3
LaunchedEffect(scaffoldState) {
scaffoldState.conceal()
}
BackdropScaffold(
scaffoldState = scaffoldState,
appBar = {
TopAppBar(
title = { Text("Backdrop scaffold") },
navigationIcon = {
if (scaffoldState.isConcealed) {
IconButton(onClick = { scope.launch { scaffoldState.reveal() } }) {
Icon(Icons.Default.Menu, contentDescription = "Localized description")
}
} else {
IconButton(onClick = { scope.launch { scaffoldState.conceal() } }) {
Icon(Icons.Default.Close, contentDescription = "Localized description")
}
}
},
actions = {
var clickCount by remember { mutableStateOf(0) }
IconButton(
onClick = {
// show snackbar as a suspend function
scope.launch {
scaffoldState.snackbarHostState
.showSnackbar("Snackbar #${++clickCount}")
}
}
) {
Icon(Icons.Default.Favorite, contentDescription = "Localized description")
}
},
elevation = 0.dp,
backgroundColor = Color.Transparent
)
},
backLayerContent = {
LazyColumn(modifier = Modifier.background(Color.Blue)) {
items(if (selection.value >= 3) 3 else 5) {
ListItem(
Modifier.clickable {
selection.value = it
scope.launch { scaffoldState.conceal() }
},
text = { Text("Select $it", color = Color.White) }
)
}
}
},
backLayerBackgroundColor = Color.Red,
frontLayerShape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),
headerHeight = frontLayerHeightDp.dp,
frontLayerBackgroundColor = Color.White,
frontLayerContent = {
LazyColumn {
items(50) {
ListItem(
text = { Text("Item $it") },
icon = {
Icon(
Icons.Default.Favorite,
contentDescription = "Localized description"
)
}
)
}
}
}
)
}
BackdropScaffold is creating a Surface for from layer under the hood, when you create your own inside frontLayerContent it's displayed on top of built-in one.
Instead use frontLayerShape and frontLayerBackgroundColor parameters:
frontLayerShape = BottomSheetShape,
frontLayerBackgroundColor = Color.White,
frontLayerContent = {
LazyColumn(
modifier = Modifier.padding(16.dp)
) {
items(
items = moorings,
itemContent = { mooring ->
...
}
)
}
}
p.s. some comments about your code:
When you have modifier parameter, you should only apply it for the topmost container in your view - here you've applied it for content of frontLayerContent, which may cause unexpected behaviour.
You don't need to wrap LazyColumn in a Column - it has no effect when Column has only one child, and if you need to apply a modifier you can do it directly for LazyColumn
In a simple AlertDialog like the following
AlertDialog(
modifier = Modifier,
title = {
Text(text = "Title")
},
text = {
Column(
modifier = Modifier.fillMaxWidth()
) {
TextButton() {
Text("Text 1")
}
TextButton() {
Text("Text 2")
}
}
},
confirmButton = {},
dismissButton = {}
)
how can I set a spacing between title and the first TextButton?
I tried to set a .padding(top = X.dp) to the Column, or the first text button, but this seems to only create a space at the bottom of the AlertDialog.
Also setting a custom .height(X.dp) did not work.
I'm using Compose 1.0.3
As #Abhimanyu perfectly explains why it's not working right now, here's the workaround I'm using to achieve the desired padding: putting the title in the content. AlertDialog's title param is optional, so it can be omitted/set to null, and instead the actual title can be put in the text parameter (which holds the dialog content).
#Composable
fun MyComposable() {
AlertDialog(
title = null,
text = {
Column {
Text(
modifier = Modifier.padding(vertical = 16.dp),
text = "Actual title"
)
// Rest of the dialog content
}
}
)
}
This is NOT an answer. It only provides info on why this is not possible.
The requirement seems not achievable at this point (6th Oct 2021) with the current compose version (1.0.3).
Will update this once that is possible.
The AlertDialog code does not respect the padding values provided.
AlertDialog.kt
// Baseline distance from the first line of the text to the last line of the title
private val TextBaselineDistanceFromTitle = 36.sp
The text offset used for the positioning is calculated like this.
val textOffset = if (titlePlaceable == null) {
TextBaselineDistanceFromTop.roundToPx()
} else {
TextBaselineDistanceFromTitle.roundToPx()
}
The distance between the first text in the text composable and the last text in the title composable is always 36.sp.
The Alert Dialog code in compose seems too hackish currently and I could see a few TODO's in the code.
Hopefully, the code will be changed to handle more scenarios soon.
I'm using this composable as first child inside Column
#Composable
fun HackySpacer(space: Dp) {
Box(
modifier = Modifier
.height(space)
.fillMaxWidth()
) {
Text(text = "")
}
}
It's not perfect, but it works for my usecase.
Is now possible using the new AlertDialog from Compose Material 3.
The default spacing between title and text is much more reasonable and it is also possible to add Modifier.padding() or Spacer() to both.
implementation("androidx.compose.material3:material3:1.0.0-alpha01")
androidx.compose.material3.AlertDialog(
onDismissRequest = {
openDialog.value = false
},
title = {
Text(text = "Title", modifier = Modifier.padding(50.dp))
},
text = {
Spacer(Modifier.height(50.dp))
Text(text = "Turned on by default")
},
confirmButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text("Confirm")
}
},
dismissButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text("Dismiss")
}
}
)
Image I have a normal Button in Android and a Star icon. I would like to compose them into a new Button icon, where the star is in one of the upper corners like here:
When I use Row both are seperated. As you can see, the star shall overlap the Button in one of its corner. How can I do that?
EDIT: Thanks to Gabriele Mariotti I used
Box {
Button(
id = "btnButton",
modifier = Modifier
.padding(end = 48)
onClick = {
//..
}
)
IconWithStar(
modifier = Modifier
.scale(0.65f)
)
}
Star icon is bound to upper left corner, how would I modify that?
You can wrap the composables with a Box and use the align/offset modifier to adjust the positions of them.
Box(Modifier.padding(top=40.dp)){
Button(
onClick = {})
{
Text("Hello World")
}
Icon(
Icons.Filled.Star, "",
modifier =Modifier
.align(TopEnd)
.offset(12.dp,-12.dp),
tint = Yellow600
)
}
To have more control you can build a custom Layout.
Something like:
Layout( content = {
Button(
modifier = Modifier.layoutId("button"),
onClick = { /* ... */ })
{
Text("Hello World")
}
Icon(Icons.Filled.Star, "",
Modifier.layoutId("icon"),
tint = Yellow600)
}){ measurables, incomingConstraints ->
val constraints = incomingConstraints.copy(minWidth = 0, minHeight = 0)
val buttonPlaceable =
measurables.find { it.layoutId == "button" }?.measure(constraints)
val iconPlaceable =
measurables.find { it.layoutId == "icon" }?.measure(constraints)
//align the icon on the top/end edge
layout(width = widthOrZero(buttonPlaceable) + widthOrZero(iconPlaceable)/2,
height = heightOrZero(buttonPlaceable)+ heightOrZero(iconPlaceable)/2){
buttonPlaceable?.placeRelative(0, heightOrZero(iconPlaceable)/2)
iconPlaceable?.placeRelative(widthOrZero(buttonPlaceable)- widthOrZero(iconPlaceable)/2,
0)
}
}
internal fun widthOrZero(placeable: Placeable?) = placeable?.width ?: 0
internal fun heightOrZero(placeable: Placeable?) = placeable?.height ?: 0
I'm currently using a dropdownmenu for selecting one of many options in my app. The problem is that the dropdownmenu expands above where it is originally anchored once it has many elements in it (see images attached). How can I force the drop down menu to stay anchored to the bottom of the button as in the first image? Thanks!
what i want (only works with few items in the list)
the problem (occurs when there is lots of items in the list)
Edit: here is the relevant code:
Box(modifier = Modifier.fillMaxWidth()) { // box for dropdown menu
Button(
modifier = Modifier.fillMaxWidth(),
onClick = { showCategories = true }
) {
Icon(Icons.Default.Favorite, null)
Text("${currentCategory.name}")
Icon(
painter = painterResource(id = R.drawable.ic_baseline_expand_more_24),
contentDescription = "expand more"
)
}
DropdownMenu(
expanded = showCategories,
onDismissRequest = {
showCategories = false
}
) {
categories.forEach {
DropdownMenuItem(
onClick = {
onCategoryChangeRequest(it)
showCategories = false
}
) {
Text(it.name)
}
}
}
}
You can assign a max size for your DropdownMenu.
DropdownMenu(
modifier = Modifier.requiredSizeIn(maxHeight = 200.dp),
...
)
It worked for me...