android - 创建已附加 View 的副本

标签 android android-view

我目前正在尝试扩展一个布局,最终将其添加到垂直 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/

相关文章:

android - Kotlin with Room and Dagger - 编译错误

android - View 如何检测它何时附加到其父 View ?

java - 如何突出显示 Canvas 上的特定矩形

android - SurfaceView 和 ImageView 的区别

iPhone 应用程序端口到 Palm Pre 或 Android?

android - 具有layout_height ="wrap_content"的android XML布局中的ImageView具有顶部和底部填充

android - 选中和取消选中 ListView 中的所有复选框

java - 更改 CalendarView 中的 "Month"文本颜色

android - 动画和可见性串联问题

Android Messenger 应用程序使用服务