调整AlertDialog内的EditText的大小

时间:2012-02-19 01:10:41

标签: android android-layout

我正在寻找一种方法来调整EditText内部AlertDialog的大小(因此它不会触及边缘)。

enter image description here

我的示例代码

AlertDialog.Builder alert = new AlertDialog.Builder(myActivity.this);

alert.setTitle("Test");

EditText textBox = new EditText(myActivity.this);
alert.setView(textBox);

alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // do nothing 
    }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
});

alert.show();

我尝试过这里提供的解决方案但没有成功:

1 个答案:

答案 0 :(得分:23)

在linearlayout中添加您的edittext并将边距设置为该布局。见下文:

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Test");

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
         LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    params.setMargins(20, 0, 30, 0);

    EditText textBox = new EditText(myActivity.this);
    layout.addView(textBox, params);

    alert.setView(layout);

    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        // do nothing 
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
    // do nothing
    }
    });

    alert.show();