你可以在一个单独的xml文件中定义你的单项 "原型",然后在代码中动态地将该文件中的项目充气,并将它们插入你的线性布局中。
然后,你将在实际的项目上定义间距,而不是在父线性布局上,(例如,作为一个android:layout_marginTop
),当你膨胀它们时,该间距将被应用于所有的项目。
EDIT:
container.xml。
<LinearLayout
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Your items will be added here -->
</LinearLayout>
item.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is my child" />
</LinearLayout>
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);
我没有花力气测试这段代码,但它 "应该 "能按原样工作 :-)