android – Dynamically add TableRow to TableLayout-ThrowExceptions

Exception or error:

When a button is clicked, the following method is run:

public void createTableRow(View v) {
  TableLayout tl = (TableLayout) findViewById(R.id.spreadsheet);
  TableRow tr = new TableRow(this);
  LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  tr.setLayoutParams(lp);

  TextView tvLeft = new TextView(this);
  tvLeft.setLayoutParams(lp);
  tvLeft.setBackgroundColor(Color.WHITE);
  tvLeft.setText("OMG");
  TextView tvCenter = new TextView(this);
  tvCenter.setLayoutParams(lp);
  tvCenter.setBackgroundColor(Color.WHITE);
  tvCenter.setText("It");
  TextView tvRight = new TextView(this);
  tvRight.setLayoutParams(lp);
  tvRight.setBackgroundColor(Color.WHITE);
  tvRight.setText("WORKED!!!");

  tr.addView(tvLeft);
  tr.addView(tvCenter);
  tr.addView(tvRight);

  tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}

R.id.spreadsheet is an xml TableLayout. I can see from debugging that the method is being accessed, but nothing is drawn to the screen. What gives? Do I need to reset the Content View somehow?

How to solve:

As it turns out, Eclipse is not always right. Ctrl+Shift+M made the wrong import. It had import android.view.ViewGroup.LayoutParams when it should have import android.widget.TableRow.LayoutParams

Everything works fine now.

Leave a Reply

Your email address will not be published. Required fields are marked *