Reputation: 5078
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
Upvotes: 0
Views: 213
Reputation: 1338
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.
Upvotes: 1