ask ask - 1 year ago 119
Android Question

How to dynamically add fields in table in Android?

I need the user to enter graph coordinates. Problem is, I don't know how many. So I want to have an "Add Point" button which inserts two fields (for x and y coordinates) into a new table row for the user to add more coordinates.

Also, how do I identify these new fields when I want to get data from them? Normally, I already know the ID of the field and call them using findViewById(; Now what do I do to identify them?

I'm writing all these coordinates into a file, so if there's a way to write them without identifying each one, please help.


I can't get the edittext fields to have these layout parameter properties:


Here's my JAVA code for the same:

TableLayout table = (TableLayout) findViewById(;

TableRow tr = new TableRow(this);
LinearLayout.LayoutParams trparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

cg[i] = new EditText(this);
weight[i] = new EditText(this);
LinearLayout.LayoutParams fieldparams = new LinearLayout.LayoutParams(100, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);



Please help if you can.

Answer Source

You can create new rows (or any other kind of View) like this:

TableRow tr = new TableRow(myContext); // usually myContext is 'this'

you then add the tr to whatever the parent view is

TableLayout myTable = findViewById(;

LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

You'll need to add layoutParams to the view before you add it since all Views have to, at minimum, specify their layout width and layout height.

If you need to add children to your row (obviously you will, what use is it otherwise) you just repeat the process except now you create an EditText. Once you do, you automatically have a reference to it, since you created it! :)

I'm not clear on what you mean by the last part of your question, where you're writing them to a file. Please elaborate.

Oh, and welcome to Stack... if you find answers useful, don't forget to up-vote them and/or mark them as correct.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download