How to change the size of an Edittext contained in a Alertdialog?

Asked

Viewed 160 times

1

I have a problem, inside a Alertdialog there is an Edittext, but it always gets very big and very close to the margins, I want to make it smaller and centered in the middle of Alertdialog, I tried to give padding but I was not successful

My code is like this:

 private void Add(){

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

    alertDialog.setTitle("Adicionar Contato");
    alertDialog.setMessage("Email do contato");
    alertDialog.setCancelable(false);

    int textoBranco = Color.WHITE;

    final EditText editText = new EditText(getApplicationContext());
    alertDialog.setView(editText);
    editText.setTextColor(textoBranco);

Ela está assim

I want to make this text field smaller

2 answers

2

You need to set the gravity to align the text and the TextSize to change the font size:

    EditText editText = new EditText(getApplicationContext());
    editText.setGravity(Gravity.CENTER); // alinhado ao centro
    editText.setTextSize(TypedValue.COMPLEX_UNIT_SP ,8); // 8 sp 
    editText.setTextColor(textoBranco);
    alertDialog.setView(editText);

To use the dp instead of sp, use the constant COMPLEX_UNIT_DIP thus:

    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP ,8); // 8 dp

Related:

What is the difference between px, dp, Dip and sp?

Editing

To set the padding:

 editText.setPadding(30,30,30,30);
        //           ^  ^  ^  ^
        //           esquerdo  topo  direito  abaixo

To do so in dp you need to make a conversion:

    int dp = 8; // tamanho que você quer
    float escala = getResources().getDisplayMetrics().density; 
    int dpFinal = (int)(dp * escala + 0.5f); 
    editText.setPadding(dpFinal,dpFinal,dpFinal,dpFinal); // insere nos lugares
    //                    ^         ^     ^        ^
    //                    esquerdo  topo  direito  abaixo

Source

  • The code solved the problem of aligning the text, but did not decrease the size of Edittext

  • @Bulletsentence I did an edit on it, try now.

  • Still nothing, the command is decreasing the size of the text, but I want to decrease is the box where the text is typed, leave it with padding 8dp

  • @Bulletsentence has worked now?

  • 1

    It worked, but creating a Batman for him!

  • @Bulletsentence blz mano! Anything from a "save" here! = ) Hug!

Show 1 more comment

2

Do the following:

LayoutParams params = new LayoutParams(50,30); // Largura, Altura
EditText editText = new EditText(getApplicationContext());
editText.setPadding (10,10,10,10); // esquerda, cima, direita, baixo
editText.setLayoutParams(params);

And if you need to turn some value to the police can use:

int valor = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <valor>, getResources().getDisplayMetrics());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.