15

我最近遇到了一個問題,我在過去幾年裏已經有好幾次了。如何僅指定一次LinearLayout的元素間距?

LinearLayout是一個非常方便layout manager。但是我完全錯過了在單個XML標籤中添加元素之間的特定空間(如填充)的可能性。

我的意思由一個標籤是,我可以在的LinearLayout的聲明定義的元素之間的間隔(例如,在垂直的LinearLayout此佈局中兩個元件之間的垂直空間)。

我知道我可以通過添加XML標籤android:layout_marginTop或類似於LinearLayout中每個元素的東西去做。

但我想只能在一個點上定義它,因爲所有元素的間距都是相同的。

有沒有人知道一個簡單的方法來做到這一點(而不是實現自定義LinearLayout或類似的東西)?我更喜歡直接在XML中工作而無需編碼的解決方案。

+0

感謝@Shrikant:在可繪製文件夾(divider.xml)

<LinearLayout android:showDividers="middle" android:divider="@drawable/divider"> 

新繪製資源。 – Dude

+0

歡迎您:) – Shrikant

+1

對於任何其他搜索[單位解決方案](http://stackoverflow.com/a/18538656/923340)。 –

回答

18

被推薦的方法是將一個樣式應用到中的所有元素線性佈局

android:style="@style/mystyle" 

<style name="mystyle"> 
     <item name="android:layout_marginTop">10dp</item> 
     ... other things that your elements have in common 
</style> 
+0

謝謝@MrFox。這是我尋找的解決方案。 – Dude

+0

很高興我可以幫忙=) –

+2

我和OP有同樣的問題。但是,我不確定這種方法如何實現我所期望的。例如,如果我的LinearLayout中有10個文本視圖,並且我希望它們之間的間距爲10dp,我希望能夠在一個地方指定10dp設置。如果我在你的例子中定義了一個樣式,我仍然必須將這個樣式應用於所有10個文本視圖。我在這裏錯過了什麼嗎? – AngieM

0

你可以在一個單獨的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); 

我還沒有把努力在測試代碼,但它「應該」的工作如:-)

+0

Thanks dbm。感謝您的漂亮的代碼示例。我更喜歡直接在XML中工作的解決方案,但如果沒有更好的解決方案出現,我會選擇你的答案。 – Dude

+0

我明白了。不幸的是我不知道純粹的純XML解決方案。 – dbm

+1

千萬不要在Android中使用5dp。始終使用4,8,16,32,48 dp。 http://developer.android.com/design/style/metrics-grids.html – Fred

1

@克里斯鬱金香的答案真的幫助了我 - 也有良好的實踐。

對於那些你們誰可能會得到關於Android的包丟失資源標識符爲「風格」 Eclipse的錯誤,像我一樣,你不需要添加Android的命名空間。

所以, 機器人:風格= 「XX」 帶來了錯誤,而風格= 「xx」 是正確的。時髦,但對於任何有這種錯誤的人來說,這可能會有所幫助。

0

您應該添加android:layout_marginTopandroid:layout_marginLeft到必須縮進元素。取決於您的LinearLayoutandroid:orientation

3

設置自定義透明繪製作爲佈局分頻器:

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android = "http://schemas.android.com/apk/res/android"> 
    <size 
    android:width = "0dp" 
    android:height = "16dp"/> 
</shape> 
相關問題