0

How do I set the margins of my TextInputEditText programmatically in Kotlin in a AlertDialogBuilder?

val input = TextInputEditText(context!!)
            input.gravity = Gravity.CENTER
            CommonHelper.capitalizeTextbox(input)
            input.inputType =
                InputType.TYPE_CLASS_TEXT
            input.setSingleLine()
            input.gravity = Gravity.CENTER

            val lp: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )

            input.layoutParams = lp
            setMargins(input, 50,10,50,10)
            alertDialog.setView(input)
            alertDialog.setIcon(R.drawable.ic_plate)


private fun setMargins(view: View, left: Int, top: Int, right: Int, bottom: Int) {
    if (view.layoutParams is MarginLayoutParams) {
        val p = view.layoutParams as MarginLayoutParams
        p.setMargins(left, top, right, bottom)
        view.layoutParams = p
        view.invalidate()
    }
}

I tried lp.setMargins(50, 10, 50, 10) but it doesn't work too

Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

1 Answers1

1

You did the correct approach by setting the margin on the layoutParams. The miss here is that you have to apply the layout params back to the view and call invalidate().

So your setMargins function code should look like below:

private fun setMargins(view: View, left: Int, top: Int, right: Int, bottom: Int) {
    if (view.layoutParams is ViewGroup.LayoutParams) {
        val p = view.layoutParams
        p.setMargins(left, top, right, bottom)
        // Set the layout params back to the view
        view.layoutParams = p
        // Call invalidate to redraw the view
        view.invalidate()
    }
}

EDIT: The if check for MarginLayoutParams instance check won't be satisfied because your params are of the LinearLayoutParams type.

enter image description here

Mohit Ajwani
  • 1,328
  • 12
  • 24
  • Thank you Sir. But still it doesn't work. I still cannot see the margins. The inputbox is still occupying the whole dialog builder. Please see my edit. – Ibanez1408 Jul 11 '21 at 05:49
  • Sir I checked the code. You are doing a MarginLayoutParams instance check which won't satisfy because it will be of the LinearLayoutParams or ViewGroup.LayoutParams type of instance. – Mohit Ajwani Jul 11 '21 at 06:21
  • Please check the updated code. I changed the instance check and the first statement inside the if block. Please try this, it should work. – Mohit Ajwani Jul 11 '21 at 07:51