【发布时间】:2011-12-17 02:34:53
【问题描述】:
使用 LayoutInflater,我动态生成多个 TableRows,每个 TableRows 都包含一个复选框。在您旋转显示器之前,一切都很好。每个 CheckBox 获得与创建的最后一个 CheckBox 相同的文本和选中状态。
我发现,如果我为每一行和每个复选框分配一个唯一的 ID,它就可以正常工作(每个复选框都保持其唯一的文本和选中状态)。
如果多次膨胀同一个布局,我是否需要为膨胀布局内的每个视图分配一个唯一的 ID?如果您有一个正在膨胀的相关布局,那肯定会很痛苦。
这是我的有效代码:
主要活动
public class PrototypeActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TableLayout tablesLayout = (TableLayout)findViewById(R.id.TableLayout1);
tablesLayout.removeAllViews();
String[] values = new String[] { "Item 1", "Item 2", "Item 3"};
for (int i = 0; i < values.length; i++) {
View view = inflater.inflate(R.layout.row_layout, null, false);
view.setId(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.tableCollectCheckBox);
checkBox.setId(values.length+i);
checkBox.setText(values[i]);
tablesLayout.addView(view);
}
tablesLayout.invalidate();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableLayout
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
</LinearLayout>
</ScrollView>
</FrameLayout>
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal">
<CheckBox
android:id="@+id/tableCollectCheckBox"
android:text="DataTable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</TableRow>
【问题讨论】: