在Android AlertDialog中添加更大的边距给EditText

AlertDialog中有一个EditText。 看起来像这样

在这里输入图像说明

看看它说tddjdjck,它是如何缩进了很多。 这是我想要的(我用setPadding左右设置为50),但我也希望它下面的蓝线也是缩进。 我怎么做?

我使用的代码如下:

  final AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity); final EditText input = new EditText(thisActivity); input.setSingleLine(); input.setPadding(50, 0, 50, 0); alert.setTitle("by..."); alert.setMessage("enter the name of the person who did:"); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString().trim(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); alert.show(); 

谢谢

Related of "在Android AlertDialog中添加更大的边距给EditText"

 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); 

确保将另一行添加到您的dimens.xml资源文件中,例如

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

您可以在setView方法中传递间距参数

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

所以,在你的情况下,你可以试试这个

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

这里是Kotlin扩展function,用于Builder设置EditText视图。

 fun android.support.v7.app.AlertDialog.Builder.setEditText(editText: EditText): AlertDialog.Builder { fun dpToPixel(dp: Float, context: Context): Float { val resources = context.resources val metrics = resources.displayMetrics return dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) } val container = FrameLayout(context) container.addView(editText) val containerParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT ) val margins = 16F containerParams.topMargin = dpToPixel(margins / 2, context).toInt() containerParams.leftMargin = dpToPixel(margins, context).toInt() containerParams.rightMargin = dpToPixel(margins, context).toInt() container.layoutParams = containerParams val superContainer = FrameLayout(context) superContainer.addView(container) setView(superContainer) return this } 

用法示例

 val editText = EditText(this) editText.hint = "Hint" AlertDialog.Builder(this) .setTitle("Title") .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() 

结果

结果