在AlertDialog中为EditText设置边距

10

我在我的Android应用程序中创建了一个带有EditText的AlertDialog,但默认边距看起来很奇怪。我尝试通过以下方式指定边距:

  android.support.v7.app.AlertDialog.Builder builder =  new android.support.v7.app.AlertDialog.Builder(SpinActivity.this);
            builder.setTitle("Edit Spin Tags");
            builder.setMessage("(separate tags with commas)");

            // set input
            int margin = 10;
            final EditText input = new EditText(SpinActivity.this);
            input.setSingleLine();
            input.setText(spinTags.toString().replace("[", "").replace("]", ""));
            builder.setView(input, margin, 0, margin, 0);

然而,从下面的图片可以看出,它没有应用所需的效果。

在这里输入图片描述

我尝试过的其他选项包括将输入放置在LinearLayout中,并在将AlertDialog视图设置为LinearLayout之前使用LayoutParams设置边距。

如何为AlertDialog中的EditText设置边距?


尝试使用此答案提供的解决方案:https://dev59.com/oXrZa4cB1Zd3GeqP4Zqx - wanpanman
@wanpanman 刚刚尝试了一下,但不幸的是没有任何效果。 - scientiffic
3个回答

9

实际上,您的解决方案完美运行,只是builder.setView(input, margin, 0, margin, 0);接受“像素”值作为参数。因此,20的值非常小。要么使用更高的边距值,例如100多个像素,要么使用此函数将dp转换为像素。

public static int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

然后,

int margin = dpToPx(20);

6
您可以将LinearLayout作为EditText的父级。然后为EditText提供边距。
private void createDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Demo");
    builder.setMessage("Some demo message");
    LinearLayout parentLayout = new LinearLayout(this);
    EditText editText = new EditText(this);
    editText.setHint("Some text");
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);

    // call the dimen resource having value in dp: 16dp
    int left = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin));
    int top = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin));
    int right = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin));
    int bottom = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin));

    // this will set the margins
    layoutParams.setMargins(left, top, right, bottom);

    editText.setLayoutParams(layoutParams);
    parentLayout.addView(editText);
    builder.setView(parentLayout);
    builder.setPositiveButton("OK", null);
    builder.create().show();
}

private int getPixelValue(int dp) {
    Resources resources = getResources();
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            dp, resources.getDisplayMetrics());
}

您可以访问http://www.pcsalt.com/android/set-margins-in-dp-programmatically-android/获取更多相关信息。


谢谢您的建议,但这没有任何影响。 - scientiffic

0

在一个不同的布局文件中定义你的EditText,同时在该布局中设置适当的边距。然后填充该布局并将其设置为对话框的视图。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接