我正在尝试在我的 Activity 中动态添加表格行。表格行处于相对布局中。它看起来不错,但不知道我要去哪里错了。下面是我的代码
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>
请帮助。
最佳答案
它正在崩溃,因为 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);
}
看看它是否有效。
关于android - 如何从 xml 文件动态添加 View ,我想在 RelativeLayout 中添加 TableRow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5285274/