你可以在一个单独的XML文件中定义单个项目的“原型”,然后从文件膨胀的项目,在代码中动态,并将其插入到您的线性布局。
然后,您将定义实际项目上的间距,而不是父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);
我还没有把努力在测试代码,但它“应该”的工作如:-)