2016-07-26 24 views
3

如何在LinearLayout中在約束佈局中平均佔用空間?
例如,如果下面的佈局是用約束書寫的,會怎樣呢?如何模仿具有約束佈局的加權LinearLayout

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal"> 

    <TextView 
    android:id="A" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" /> 

    <TextView 
    android:id="B" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" /> 

    <TextView 
    android:id="C" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" /> 

    <TextView 
    android:id="D" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" /> 
</LinearLayout> 

在約束佈局,我可以設置AD到邊緣,A←B→D帶33個偏壓和A←C→D用66個偏壓種具有各元件之間具有相等的空間。
該解決方案雖然並沒有真正擴展。

有沒有一種合適的方法在約束佈局中做到這一點?

+0

你真的需要直接在ConstraintLayout的項目,或者你可以把他們在的LinearLayout,並把LinearLayout中進ConstraintLayout – lionscribe

+0

@lionscribe ConstraintLayout在這裏除了別的以外,還可以製作平面設計和幫助表演。因此,我正在尋找一種平坦的方式來完成此任務,而無需其他任何嵌套佈局。 – oldergod

+0

在https://developer.android.com/training/constraint-layout/index.html有這方面的新文檔 –

回答

12

FYI - Constraint Layout alpha 9添加Chains,它允許您實現此行爲。

enter image description here

+0

剛剛在Twitter上看到。感謝您的辛勤工作。 – oldergod

+0

你可以請更新任何示例代碼。我無法在Android Studio 2.2.2佈局編輯器中找到這個選項,如添加垂直指南並添加水平指南 – ramji

+0

@ramji它在2.2.2 UI中不可用,您現在必須修改XML。您可以通過https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html查看Chains文檔。 –

7

目前(約束佈局alpha 6),唯一的選擇是使用百分比位置的垂直指引,然後對每個小工具以這種方式約束他們到指導: 左側< - 小工具A - >準則1 < - 控件B - >準則2 < - 控件C - >右側

準則1在0.33,準則2在0.66。

但是。如果你想要的只是這個確切的行爲,只需使用線性佈局(甚至在約束佈局內)即可。雖然它的工作原理,我懷疑它會比使用線性佈局這個特定任務更快。它給你提供約束佈局的唯一好處是你可以只爲一個給定的軸定義這種行爲,另一個軸可以完全不同的約束(而對於LL它將被對齊 - 但這是常見的需要) 。

雖然我們有計劃讓這個特定行爲在約束佈局的未來版本中更容易做,但這並不意味着所有現有的佈局都不應該再被使用。

+0

我使用了一種類似的方法,但是如你所知,它不能縮放;我們需要重新定義這些指南,如果一個小部件被添加/刪除。無論如何感謝您的支持。 – oldergod

+1

是的 - 這就是爲什麼我們打算在ConstraintLayout中爲此添加另一個機制。但在這種情況下使用線性佈局也很好。 –

0

例如:

<Button 
    android:id="@+id/btn_a" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="ButtonA" 
    app:layout_constraintHorizontal_chainStyle="spread" 
    app:layout_constraintLeft_toLeftOf="parent" 
    app:layout_constraintRight_toLeftOf="@+id/btn_b" /> 

<Button 
    android:id="@+id/btn_b" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="ButtonB" 
    app:layout_constraintLeft_toRightOf="@+id/btn_a" 
    app:layout_constraintRight_toLeftOf="@+id/btn_c" /> 

<Button 
    android:id="@+id/btn_c" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="ButtonC" 
    app:layout_constraintLeft_toRightOf="@+id/btn_b" 
    app:layout_constraintRight_toRightOf="parent" />