I've created an AlertDialog with an EditText in my Android app, but the default margins look really off. I've tried to specify margins as follows:
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);
However, from the image below, you can see that it is not applying the desired effect.
Other options I've tried including placing the input in a LinearLayout and setting the margins using LayoutParams before setting the AlertDialog view to the LinearLayout.
How do I set the margins for an EditText in an AlertDialog?
Actually your solution is working perfectly, except that builder.setView(input, margin, 0, margin, 0);
takes arguments in "pixel" values. So a value of 20 is very small. Either use a higher value for margin e.g. in the 100s. or use this function to convert from dp to pixels
public static int dpToPx(int dp)
{
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
and then,
int margin = dpToPx(20);
You can have a LinearLayout
as parent of the EditText
. Then provide the margin to the 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());
}
For more you can visit http://www.pcsalt.com/android/set-margins-in-dp-programmatically-android/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With