Android 动态添加 TableRow 到 TableLayout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3200691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:07:47  来源:igfitidea点击:

Dynamically add TableRow to TableLayout

android

提问by dfetter88

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.spreadsheetis 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?

R.id.spreadsheet是一个 xml TableLayout。我可以从调试中看到该方法正在被访问,但没有任何内容被绘制到屏幕上。是什么赋予了?我需要以某种方式重置内容视图吗?

回答by dfetter88

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

事实证明,Eclipse 并不总是正确的。Ctrl+Shift+M 导入错误。它import android.view.ViewGroup.LayoutParams应该有import android.widget.TableRow.LayoutParams

Everything works fine now.

现在一切正常。