3

我正在尝试在我的活动中动态添加表格行。表格行处于相对布局中。它看起来不错,但不知道我哪里出错了。下面是我的代码

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    RelativeLayout RLayout = (RelativeLayout)findViewById(R.id.RelativeLayout);
    TableRow tableRow = (TableRow)findViewById(R.id.TableRow);
    for(int i = 1; i <3; i++)
        RLayout.addView(tableRow); //My code is crashing here
}

而main.xml如下

  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout
  android:id="@+id/RelativeLayout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android"
  >
  <TableRow
  android:id="@+id/TableRow"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:layout_alignParentTop="true"
  android:layout_alignParentLeft="true"
  >
  <TextView
  android:id="@+id/Text"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Text"
  >
  </TextView>
  </TableRow>
  </RelativeLayout>

请帮忙。

4

1 回答 1

9

它崩溃了,因为它TableRow已经在布局中。如果要动态添加一些,则必须以编程方式创建它,即:

// PSEUDOCODE
TableRow newRow = new TableRow(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(/*....*/);
newRow.setLayoutParams(lp);

relLayout.add(newRow);

其实TableRow应该用在里面TableLayout

如果您想多次使用某些东西,您可以使用膨胀技术。您需要创建一个 xml 布局,其中包含您要重复的唯一部分(因此您TableRow及其子项),然后:

LayoutInflater inflater = 
              (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View inflated = inflater.inflate(R.layout.your_layout, null);

现在inflated包含您指定的布局。而不是null,您可能希望在其中放置附加膨胀的布局。每次你需要一个这样的新元素时,你都必须以同样的方式给它充气。

(您应该始终报告崩溃时遇到的错误)

- - - 编辑 - - -

好的,现在我明白了,这是您的代码:

RelativeLayout RLayout = (RelativeLayout)findViewById(R.id.RelativeLayout);
TableRow tableRow = (TableRow)findViewById(R.id.TableRow);

for(int i = 1; i <4; i++) {
    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View inflated = inflater.inflate(R.layout.main, tableRow);
}

这样,您就可以在原始 TableRow 中膨胀整个布局。

您应该有这样的row.xml布局,以及main.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/TableRow"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:layout_alignParentTop="true"
  android:layout_alignParentLeft="true"
  >
  <TextView
  android:id="@+id/Text"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Text"
  />
  </TableRow>

然后像这样充气:

RelativeLayout RLayout = (RelativeLayout)findViewById(R.id.RelativeLayout);

for(int i = 1; i <4; i++) {
    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.row, RLayout);
}

看看它是否有效。

于 2011-03-12T21:07:33.010 回答