Android 在AlertDialog中设置EditText的边距
我在Android应用程序中创建了一个带有EditText的AlertDialog,但是默认的边距看起来很差。我已尝试按如下方式指定边距:Android 在AlertDialog中设置EditText的边距,android,android-alertdialog,Android,Android Alertdialog,我在Android应用程序中创建了一个带有EditText的AlertDialog,但是默认的边距看起来很差。我已尝试按如下方式指定边距: android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(SpinActivity.this); builder.setTitle("Edit Spin Tags");
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的边距?在不同的版面文件中定义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());
}
要了解更多信息,您可以访问事实上,您的解决方案运行良好,除了builder.setView(输入,边距,0,边距,0)代码>以“像素”值为参数。因此,值20非常小。或者使用更高的裕度值,例如100秒。或者使用此函数将dp转换为像素
public static int dpToPx(int dp)
{
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
然后呢,
int margin = dpToPx(20);
尝试这个答案的解决方案@wanpanman刚刚尝试了这个,但没有效果,不幸的是,这个建议没有效果