ask ask - 2 months ago 18
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(R.id.ID_here); 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.

EDIT:

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

android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="numberDecimal"


Here's my JAVA code for the same:

TableLayout table = (TableLayout) findViewById(R.id.TableLayout1);

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

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

tr.addView(cg[i]);
tr.addView(weight[i]);

table.addView(tr);


Please help if you can.

Answer

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(R.id.TableLayout1);

LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(lp);
myTable.addView(tr);

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.