0

In compose desktop we have Dialog and AlertDialog.

If use Dialog, it has no parent and it's aligned center of the screen by default. To align it to window center we can calculate diffirence between window and dialog center point offset and get offset need to be added for dialog start position:

fun getOffset(wState: WindowState, dState: DialogState): DpOffset {
    
    val winCenterPoint = DpOffset(
        wState.position.x + wState.size.width / 2,
        wState.position.y + wState.size.height / 2
    )
    
    val dlgCenterPoint = DpOffset(
        dState.position.x + dState.size.width / 2,
        dState.position.y + dState.size.height /2
    )
    
    return winCenterPoint - dlgCenterPoint
    
}

But here is a problem: If Window or Dialog size is unspecified, we're not be able to calculate offset. Also if Window/Dialog is centered on the screen - state.position will return Alignment instead of Offset.

If use AlertDialog it centered by parent bounds. This one throw exception when I set as buttons parameter custom composable dialog:

enter image description here

AlertDialog based on Popup underhood, but when I set same composables to Popup it doesn't crash, think it's someting with measuring inside window.

If somebody have a better way to align Dialog to Window center, share pls your knowlage.

Exicode
  • 23
  • 6

1 Answers1

1

The documentation of Compose desktop is very poor and weak and there is no tutorial for this , but you can try to center your window and the dialog should be centered,

val windowState = rememberWindowState(position = WindowPosition(Alignment.Center))
Window(onCloseRequest = ::exitApplication, state = windowState) {}
Ahmed Hnewa
  • 1,185
  • 1
  • 4
  • 14
  • 1
    I save app window position into settings file, thats why i need to center dialog inside window not on screen. – Exicode Sep 15 '22 at 01:15