我想将表格行动态添加到我的布局中,这些行将被添加到名为 main_ScrollView_Container 的相对布局中
我遇到的问题是:
- 添加的
- 行按添加顺序堆叠在彼此的顶部,而不是彼此下方堆叠。 如何检索添加的行
- ,以便可以读取/写入已添加的每一行的 EditText输入和 TextView输出?
我的创造:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
// the inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// the item to inflate
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.main_ScrollView_Container);
// the item to inflate with
View tableRow = inflater.inflate(R.xml.my_row, relativeLayout, false);
relativeLayout.addView(tableRow, 0);
tableRow = inflater.inflate(R.xml.my_row, relativeLayout, false);
relativeLayout.addView(tableRow, 1);
tableRow = inflater.inflate(R.xml.my_row, relativeLayout, false);
relativeLayout.addView(tableRow, 2);
tableRow = inflater.inflate(R.xml.my_row, relativeLayout, false);
relativeLayout.addView(tableRow, 3);
// retrieve/set values to the EditText input
// retrieve/set values to the TextView output
}
我得到了这个my_row.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="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" >
<EditText
android:id="@+id/input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:ems="10"
android:gravity="center"
android:hint="@string/input"
android:inputType="numberDecimal" />
<TextView
android:id="@+id/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:hint="@string/output"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
和我的布局
<ScrollView
android:id="@+id/main_scroll_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="@+id/main_ScrollView_Container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</RelativeLayout>
</ScrollView>
首先,您可能应该使用R.layout
而不是R.xml
来组织和引用布局文件。仅在项目中就有许多类型的 xml 资源 - 最好对它们进行子分类。
其次,当您调用relativeLayout.addView(tableRow, 0);
时,您实际上是在布局的第 0 个位置(顶部)添加tableRow
。此外,由于您要将行添加到RelativeLayout
中,因此它们堆叠在一起也就不足为奇了。您可能希望改用垂直方向的LinearLayout
,这将负责从上到下垂直排列行。
第三,一旦你膨胀了你的行视图,你可以像这样访问它的子视图:
View tableRow = inflater.inflate(R.xml.my_row, relativeLayout, false);
EditText inputBox = (EditText) tableRow.findViewById(R.id.input);
TextView outputBox = (TextView) tableRow.findViewById(R.id.output);
请记住,您可以在任何View
上调用findViewById
来访问其子视图 - 前提是它们具有 ID。