Home > OS >  How to set horizontal margin in dialog when width is match parent?
How to set horizontal margin in dialog when width is match parent?

Time:09-01

I'm trying to set horizontal margin in a dialog fragment where width is match parent but margin never applies. This is what I'm trying:

DialogFragment:

override fun onStart(){
  super.onStart()
  val dialog = dialog
  if(dialog != null){
    dialog.window?.setGravity(Gravity.CENTER_HORIZONTAL or Gravity.TOP)
    val p = dialog.window?.attributes
    p?.horizontalMargin = 100f
    p?.width = ViewGroup.LayoutParams.MATCH_PARENT
    dialog.window?.attributes = p
  }
}

How can I set width match parent and set horizontal margin?

CodePudding user response:

If your dialog is a custom dialog - Then in XML give a horizontal margin to the root layout

Add one more attribute while initializing dialog - window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

Your modified function should be like this-

override fun onStart(){
  super.onStart()
  val dialog = dialog
  if(dialog != null){
    dialog.window?.setGravity(Gravity.CENTER_HORIZONTAL or Gravity.TOP)
    val p = dialog.window?.attributes
    p?.horizontalMargin = 100f
    p?.width = ViewGroup.LayoutParams.MATCH_PARENT
    dialog.window?.attributes = p
    window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
  }
}
  • Related