Search code examples
androidkotlinandroid-dialogfragment

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


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?


Solution

  • 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))
      }
    }