How to place Edittext next to Edit Text dynamically?

Asked

Viewed 570 times

3

I am creating a dynamic form and needed to display in a form, Age and Address on the same line. I created a "for" to create n times the same form but is giving error. follow the code:

public void form() {

    for (int i = 0; i < 3; i++) {

        TextView tv = new TextView(this);
        tv.setText("Nome");
        layout.addView(tv);
        EditText et = new EditText(this);
        et.setText("");
        layout.addView(et);

        TextView tv1 = new TextView(this);
        tv1.setText("Idade");
        layout2.addView(tv1);
        EditText et1 = new EditText(this);
        et1.setText("");
        layout2.addView(et1);

        TextView tv2 = new TextView(this);
        tv2.setText("Endereco");
        layout2.addView(tv2);
        EditText et2 = new EditText(this);
        et2.setText("");
        layout2.addView(et2);
        // AQUI COLOCO O LAYOUT HORIZONTAL DENTRO DO VERTICAL, FUNCIONA A LÓGICA, PORÈM ESTÁ DANDO ERRO POR CAUSA DO FOR
        layout.addView(layout2);

        TextView tv3 = new TextView(this);
        tv3.setText("Telefone");
        layout.addView(tv3);
        EditText et3 = new EditText(this);
        et3.setText("");
        layout.addView(et3);

    }

}

Note: layout -> Linear vertical layout layout2 - > Linear horizontal layout.

If I take the "for" out of the code, it works, but I need to use the "for". Someone can help. Thanks in advance!!!

  • Wouldn’t it be because you’re creating the fields with the same names? By Ex, if you take this one out and pick up these Texts and copy and paste three times it will show error right? Have how to show the error message?

  • That’s exactly the error message, is there any way to keep it going. Because if I take out "layout.addView(layout2);" it actually works with for.

1 answer

1

A view cannot be added 2 times within another view. You have to make the creation of layout2 dynamics.

To do this you can create this view in a separate xml and inflate each time you want a new instance.

Browser other questions tagged

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