Add bigger margin to EditText in Android AlertDialog Add bigger margin to EditText in Android AlertDialog android android

Add bigger margin to EditText in Android AlertDialog


final AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);final EditText input = new EditText(thisActivity);input.setSingleLine();FrameLayout container = new FrameLayout(thisActivity);FrameLayout.LayoutParams params = new  FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);params.leftMargin = getResources().getDimensionPixelSize(R.dimen.dialog_margin);input.setLayoutParams(params);container.addView(input);alert.setTitle("by...");alert.setMessage("test message");alert.setView(container);

Make sure you add another line to your dimens.xml resource file, such as

<dimen name="dialog_margin">20dp</dimen>


You can pass spacing parameter in setView method

alert.setView(view ,left_space , top_space , right_space , bottom_space);

So,in your case you can try this

alert.setView(input , 50 ,0, 50 , 0);


Here is Kotlin extension function for the Builder to set EditText view.

val Float.toPx: Intget() = (this * Resources.getSystem().displayMetrics.density).toInt()fun AlertDialog.Builder.setEditText(editText: EditText): AlertDialog.Builder {    val container = FrameLayout(context)    container.addView(editText)    val containerParams = FrameLayout.LayoutParams(            FrameLayout.LayoutParams.MATCH_PARENT,            FrameLayout.LayoutParams.WRAP_CONTENT    )    val marginHorizontal = 48F    val marginTop = 16F    containerParams.topMargin = (marginTop / 2).toPx    containerParams.leftMargin = marginHorizontal.toInt()    containerParams.rightMargin = marginHorizontal.toInt()    container.layoutParams = containerParams    val superContainer = FrameLayout(context)    superContainer.addView(container)    setView(superContainer)    return this}

Usage example

val editText = EditText(this)AlertDialog.Builder(this)        .setTitle("Group Name")        .setEditText(editText)        .setPositiveButton("OK", { _: DialogInterface, _: Int ->            // Do your work with text here            val text = editText.text.toString()            Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show()        })        .setNegativeButton("Cancel", null)        .show()

Result

enter image description here