您可以在单独的xml文件中定义单个项目“prototype”,然后在代码中动态扩充该文件中的项目并将它们插入到线性布局中。
然后,您可以在实际项目上定义间距,而不是父级LinearLayout(例如,作为android:layout_marginTop),并且在您向它们充气时,该间距将应用于您的所有项目。
编辑:
container.xml中:
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
item.xml:android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is my child" />
MyActivity.java:// Put this in a suitable place in your Java code, perhaps
// in "onCreate" or "onResume" depending on where and how
// you initialize your view. You can, of course inflate
// any number of instances of the item and add them to
// your parent LinearLayout.
LayoutInflater inflater = LayoutInflater.from(context);
View item = inflater.inflate(R.layout.item, null, false);
LinearLayout container = findViewById(R.id.parent);
container.addView(view);我没有努力测试代码,但它“应该”按原样工作:-)