你可以在一個單獨的XML文件中定義單個項目的「原型」,然後從文件膨脹的項目,在代碼中動態,並將其插入到您的線性佈局。
然後,您將定義實際項目上的間距,而不是父LinearLayout(例如android:layout_marginTop
),並且該間距將在您膨脹它們時應用於所有項目。
編輯:
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);
我還沒有把努力在測試代碼,但它「應該」的工作如:-)
來源
2012-09-17 07:49:19
dbm
感謝@Shrikant:在可繪製文件夾(divider.xml)
新繪製資源。 – Dude
歡迎您:) – Shrikant
對於任何其他搜索[單位解決方案](http://stackoverflow.com/a/18538656/923340)。 –