I have a row with a text align at the start and a image align at the end. When I press the image I'm showing a DropdownMenu, but this appear in the start of the row and I want that appear at the end of the row.
I'm trying to use Alignment.centerEnd in Modifier component but is not working.
How can I do that the popup appear at the end of the row?
#Composable
fun DropdownDemo(currentItem: CartListItems) {
var expanded by remember { mutableStateOf(false) }
Box(modifier = Modifier
.fillMaxWidth()) {
Text(modifier = Modifier.align(Alignment.TopStart),
text = currentItem.type,
color = colorResource(id = R.color.app_grey_dark),
fontSize = 12.sp)
Image(painter = painterResource(R.drawable.three_dots),
contentDescription = "more options button",
Modifier
.padding(top = 5.dp, bottom = 5.dp, start = 5.dp)
.align(Alignment.CenterEnd)
.width(24.dp)
.height(6.75.dp)
.clickable(indication = null,
interactionSource = remember { MutableInteractionSource() },
onClick = {
expanded = true
}))
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.background(
Color.LightGray
).align(Alignment.CenterEnd),
) {
DropdownMenuItem(onClick = { expanded = false }) {
Text("Delete")
}
DropdownMenuItem(onClick = { expanded = false }) {
Text("Save")
}
}
}
}
As documentation says:
A DropdownMenu behaves similarly to a Popup, and will use the position of the parent layout to position itself on screen.
You need to put DropdownMenu together with the caller view in a Box. In this case DropdownMenu will appear under the caller view.
var expanded by remember { mutableStateOf(false) }
Column {
Text("Some text")
Box {
Image(
painter = painterResource(R.drawable.test),
contentDescription = "more options button",
modifier = Modifier
.clickable {
expanded = true
}
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
DropdownMenuItem(onClick = { expanded = false }) {
Text("Delete")
}
DropdownMenuItem(onClick = { expanded = false }) {
Text("Save")
}
}
}
}
Use the offset parameter of the DropdownMenu().
DropdownMenu(
offset = DpOffset(x = (-66).dp, y = (-10).dp)
)
Change the x and y values. They accept both positive and negative values.
Related
I need remove the elevation/shadow from dropdown menu, like right image:
My menu:
DropdownMenu(
expanded = mExpanded,
onDismissRequest = { mExpanded = false },
modifier = Modifier
.width(with(LocalDensity.current){mTextFieldSize.width.toDp()})
) {
mCities.forEach { label ->
DropdownMenuItem(onClick = {
mSelectedText = label
mExpanded = false
}) {
Text(text = label)
}
}
}
Based on answer: How to add elevation just in the bottom of an element? Jetpack Compose you can wrap your dropdown menu in a Surface and provide the elevation as 0.
Modified code:
Surface(
shadowElevation = 0.dp
){
DropdownMenu(
expanded = mExpanded,
onDismissRequest = { mExpanded = false },
modifier = Modifier
.width(with(LocalDensity.current){mTextFieldSize.width.toDp()})
) {
mCities.forEach { label ->
DropdownMenuItem(onClick = {
mSelectedText = label
mExpanded = false
}) {
Text(text = label)
}
}
}
}
I want to show my DropdownMenu where ever I touch but it doesn't work. I used offset to set the location of my drop down menu but it doesn't work properly. It looks like it only sets the x value to the location of my drop down menu.
var expanded by remember { mutableStateOf(false) }
var touchPoint: Offset by remember { mutableStateOf(Offset.Zero) }
val density = LocalDensity.current
Box(
Modifier
.fillMaxSize()
.background(Color.Cyan)
.pointerInput(Unit) {
detectTapGestures {
Log.d(TAG, "onCreate: ${it}")
touchPoint = it
expanded = true
}
}
) {
val (xDp, yDp) = with(density) {
(touchPoint.x.toDp()) to (touchPoint.y.toDp())
}
DropdownMenu(
modifier = Modifier.align(Alignment.Center),
expanded = expanded,
offset = DpOffset(xDp, yDp),
onDismissRequest = {
expanded = false
},
) {
DropdownMenuItem(onClick = {
expanded = false
}) {
Text("Copy")
}
DropdownMenuItem(onClick = { expanded = false }) {
Text("Get Balance")
}
}
}
What you actually should be doing is offseting upward by giving a negative Offset.
You need get height of your parent you can get it via Modifier.onSizeChanged or using BoxWithConstraints if it covers whole parent.
I used BoxWithConstraints for demonstration but both can be used.
If you offset by maxHeight or height of the Composable Dropdown menu appears at the top so we need another positive offset which is y axis of touch position to move it down
#Composable
private fun DropDownSample() {
var expanded by remember { mutableStateOf(false) }
var touchPoint: Offset by remember { mutableStateOf(Offset.Zero) }
val density = LocalDensity.current
BoxWithConstraints(
Modifier
.fillMaxSize()
.background(Color.Cyan)
.pointerInput(Unit) {
detectTapGestures {
Log.d("TAG", "onCreate: ${it}")
touchPoint = it
expanded = true
}
}
) {
val (xDp, yDp) = with(density) {
(touchPoint.x.toDp()) to (touchPoint.y.toDp())
}
DropdownMenu(
expanded = expanded,
offset = DpOffset(xDp, -maxHeight + yDp),
onDismissRequest = {
expanded = false
}
) {
DropdownMenuItem(
onClick = {
expanded = false
},
interactionSource = MutableInteractionSource(),
text = {
Text("Copy")
}
)
DropdownMenuItem(
onClick = {
expanded = false
},
interactionSource = MutableInteractionSource(),
text = {
Text("Get Balance")
}
)
}
}
}
As can be seen in gif if you touch area where Dropdown appears if you touch the bottom of the screen it is moved up to top of the Composable. It's at the end of the gif. I don't know what's causing this. Other than this issue it works as expected.
I implemented a simple dialog with Jetpack Compose on Android.
I am trying to show a caution message when isRehearsal is true.
The variable isRehearsal is toggled when the user clicks buttons, and changing button works fine when the user clicks the buttons and toggles isRehearal.
The problem is, that the caution text does not appear when the initial value of isRehearsal is false and later the variable becomes true. When I change the initial value of isRehearsal to true, then the text disappears/appears fine when isRehearsal becomes false or true.
var isRehearsal by remember { mutableStateOf(false) }
Dialog(
onDismissRequest = { dismiss() },
DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true)
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.background(White, shape = RoundedCornerShape(8.dp))
.fillMaxWidth()
.padding(12.dp)
) { // the box does not resize when the caution text appears dynamically.
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(text = "Set speed")
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier.fillMaxWidth()
) {
if (isRehearsal) {
Button(
onClick = { isRehearsal = false },
colors = ButtonDefaults.buttonColors(
backgroundColor = Colors.Red400
)
) {
Text(text = "Rehearsal ON")
}
} else {
Button(
onClick = { isRehearsal = true },
colors = ButtonDefaults.buttonColors(
backgroundColor = Colors.Green400
)
) {
Text(text = "Rehearsal OFF")
}
}
Button(onClick = { onClickStart(pickerValue) }) {
Text(text = "Start")
}
}
if (isRehearsal) { // BUG!! when the intial value of isRehearsal is false, then the text never appears even when the value becomes true.
Text(text = "Rehearsal does not count as high score") // <- The caution text
}
}
}
}
How should I change the Box block to make the box's height extend properly to be able to wrap caution text when a view appears dynamically?
Edit
If I change the catuion message part to like below, the text appears fine even when the initial value of isRehearsal is false. Therefore, I think that the issue is with the height of the Box composable.
if (isRehearsal) {
Text(text = "Rehearsal does not count as high score")
} else {
Spacer(modifier = Modifier.height(100.dp))
}
You can use DialogProperties() with
usePlatformDefaultWidth = false
as a workaround. Example:
Dialog(
onDismissRequest = {},
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Card(modifier = Modifier.padding(8.dp).wrapContentSize().animateContentSize()) {
// content
}
}
It looks like the topmost Dialog view size is not getting updated after the first recomposition. It's a known bug.
As a workaround until it's fixed, you can make a transparent topmost view take all the size available, and handle clicks same as dismissOnClickOutside option does:
Dialog(
onDismissRequest = { },
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
) {
// same action as in onDismissRequest
}
) {
// content
}
}
I need to implement multiselect for LazyList, which will also change appBar content when list items are long clicked.
For ListView we could do that with just setting choiceMode to CHOICE_MODE_MULTIPLE_MODAL and setting MultiChoiceModeListener.
Is there a way to do this using Compose?
Since you're in control of the whole state in jetpack compose, you can easily create your own multi-select mode. This is an example.
First I created a ViewModel
val dirs: LiveData<DirViewState> = {
DirViewState.Content(dirRepository.targetFolders)}.asFlow().asLiveData()
val all: LiveData<DirViewState> = {
DirViewState.Content(dirRepository.allFolders)
}.asFlow().asLiveData()
val createFolder = mutableStateOf(false)
val refresh = mutableStateOf(false)
val enterSelectMode = mutableStateOf(false)
val selectedAll = mutableStateOf(false)
val selectedList = mutableStateOf(mutableListOf<String>())
fun updateList(path: String){
if(path in selectedList.value){
selectedList.value.remove(path)
}else{
selectedList.value.add(path)
}
}
}
Usage
Card(modifier = Modifier
.width(100.dp)
.height(120.dp)
.padding(8.dp)
.pointerInput(Unit) {
detectTapGestures(
onLongPress = { **viewModel.enterSelectMode.value = true** },
onTap = {
if (viewModel.enterSelectMode.value) {
viewModel.enterSelectMode.value = false
}
}
)
}
,
shape = MaterialTheme.shapes.medium
) {
Image(painter = if (dirModel.dirCover != "") painter
else painterResource(id = R.drawable.thumbnail),
contentDescription = "dirThumbnail",
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth(),
contentScale = ContentScale.FillHeight)
**AnimatedVisibility(
visible = viewModel.enterSelectMode.value,
enter = expandIn(),
exit = shrinkOut()
){
Row(verticalAlignment = Alignment.Top,
horizontalArrangement = Arrangement.Start) {
Checkbox(checked = isSelected.value, onCheckedChange = {
isSelected.value = !isSelected.value
viewModel.updateList(dirModel.dirPath)
})
}
}**
}
Add selected field to some class representing the item. Then just compose proper code based on that field. In compose you don't have to look for some LazyColumn flag or anything like that. You are in control of the whole state of the list.
The same can be said about the AppBar, you can do a simple if there, like if (items.any { it.selected }) // display button
You can simply handle this by the below code:
Fore example This is your list:
LazyColumn {
items(items = filters) { item ->
FilterItem(item)
}
}
and this is your list item View:
#Composable
fun FilterItem(filter: FilterModel) {
val (selected, onSelected) = remember { mutableStateOf(false) }
Card(
shape = RoundedCornerShape(8.dp),
modifier = Modifier
.padding(horizontal = 8.dp)
.border(
width = 1.dp,
colorResource(
if (selected)
R.color.black
else
R.color.white
),
RoundedCornerShape(8.dp)
)) {
Text(
modifier = Modifier
.toggleable(
value =
selected,
onValueChange =
onSelected
)
.padding(8.dp),
text = filter.text)
}
}
and that's it use tooggleable on your click component modifier like here I did on text.
I have an image and I want to show a dropdownMenuItem when user click in the image. I was debugging the app and I can see that the code go through the DropdownDemo method but is not showing anything.
Am I doing something wrong?
Click code:
#Composable
fun Header(currentItem: CartListItems) {
var showDialog by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Text(modifier = Modifier.align(Alignment.TopStart),
text = currentItem.type,
color = colorResource(id = R.color.app_grey_dark),
fontSize = 12.sp)
Image(painter = painterResource(R.drawable.three_dots),
contentDescription = "more options button",
Modifier
.align(Alignment.CenterEnd)
.width(24.dp)
.height(6.75.dp)
.clickable(indication = null,
interactionSource = remember { MutableInteractionSource() },
onClick = {
showDialog = true
}))
if(showDialog) {
DropdownDemo()
showDialog = false
}
}
}
Dropmenu:
#Composable
fun DropdownDemo() {
var expanded by remember { mutableStateOf(false) }
val items = listOf("A", "B", "C", "D", "E", "F")
val disabledValue = "B"
var selectedIndex by remember { mutableStateOf(0) }
Box(modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.TopStart)) {
Text(items[selectedIndex],modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { expanded = true })
.background(
Color.Gray
))
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.fillMaxWidth()
.background(
Color.Red
)
) {
items.forEachIndexed { index, s ->
DropdownMenuItem(onClick = {
selectedIndex = index
expanded = false
}) {
val disabledText = if (s == disabledValue) {
" (Disabled)"
} else {
""
}
Text(text = s + disabledText)
}
}
}
}
}
showDialog appears to be a MutableState object. Hence, when the image is clicked, it becomes true, and a recomposition is triggered, after which the conditional block is executed, displaying the DropDownMenu. However, in the very next line. You equate showDialog to false, re-trigerring a recomposition, and rendering the DropDownMenu collapsed.