Ok so i think what you want to do is something like:
- Add Empty Row
- On EditText change Recalculate
First the adding of the Empty Row:
private void AddRow(){
TableLayout tl = (TableLayout) findViewById(R.id.somelayout);
TableRow row= new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
EditText fruit = new EditText(this);
EditText freq = new EditText(this);
EditText perc = new EditText(this);
freq.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ReCalculate();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
row.addView(fruit);
row.addView(freq);
row.addView(perc);
tl.addView(row,i);
}
private void ReCalculate(){
float sum = 0f;
int rows = tl.getChildCount();
// Get the total
for (int i = 0; i < rows; i++) {
TableRow elem = (TableRow) tl.getChildAt(i);
sum+= Integer.parseInt(((EditText)elem.getChildAt(1)).getText().toString());
}
// Recalculate every row percent
for (int i = 0; i < rows; i++) {
TableRow elem = (TableRow) tl.getChildAt(i);
int amount = Integer.parseInt(((EditText)elem.getChildAt(1)).getText().toString());
((EditText)elem.getChildAt(1)).setText(String.valueOf(amount/sum*100));
}
}
Edited:
The button is not dynamically created so you don't need to call row.addView() for it or the OnClickListener. And the OnClickListener of the button will just call AddRow()
This may have some errors and you will need to check for empty texts but just wanted to give you an example. Hope it helps