我目前正在尝试扩展一个布局,最终将其添加到垂直 LinearLayout 容器中,作为更大的动态表单创建模块的一部分。
layout_checkbox.xml 如下:
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:text="sample text" />
<LinearLayout
android:id="@+id/checkboxGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<CheckBox
android:id="@+id/checkbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="sample" />
</LinearLayout>
现在,如果可能的话,我想做的是获取复选框(@+id/checkbox
)并创建它的副本,所有副本都在 LinearLayout @+id 下/checkboxGroup
。
layout = (LinearLayout) inflater.inflate(R.layout.layout_checkbox, container, false);
LinearLayout checkboxGroup = (LinearLayout) layout.findViewById(R.id.checkboxGroup);
CheckBox checkbox = (CheckBox) checkboxGroup.findViewById(R.id.checkbox);
// code that supposedly clones/duplicates checkbox.
我知道我可以轻松地从另一个 xml 定义中扩充 Checkbox 以创建它的多个实例,然后将它们添加到组中。我尝试这样做的原因是因为我正在创建某种类型的库,并且我正在尝试强制执行某种约定以使其更易于使用。
编辑:
这有效,但很容易感觉到性能受到影响:
layout = (LinearLayout) inflater.inflate(R.layout.layout_checkbox, container, false);
LinearLayout originalCheckboxGroup = (LinearLayout) layout.findViewById(R.id.checkboxGroup);
for (String entryItem : entry.fieldEntries) {
LinearLayout tempCheckboxLayout = (LinearLayout) inflater.inflate(R.layout.layout_checkbox, container, false);
LinearLayout checkboxGroup = (LinearLayout) tempCheckboxLayout.findViewById(R.id.checkboxGroup);
CheckBox checkbox = (CheckBox) checkboxGroup.findViewById(R.id.checkbox);
checkbox.setText(entryItem);
checkboxGroup.removeView(checkbox);
originalCheckboxGroup.addView(checkbox);
}
最佳答案
what I want to do if possible is to get hold of the Checkbox (@+id/checkbox) and create copies of it
不,您不能复制/克隆 View ,因为您将始终对 View 具有相同的引用,并且当一个更改时,所有 View 都会更改,唯一的方法是每次都膨胀 View (如果您愿意)使用相同的 View 。
编辑:
无法克隆/复制复选框,但您可以在每次想要使用复选框时膨胀 View (线性布局)。并使用已膨胀的复选框。每次要使用/克隆复选框时都执行此操作。
关于android - 创建已附加 View 的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24948189/