2012-07-31 11 views
16

Czy można zmniejszyć marginesy w systemie Android? Powiedzmy, że mam LinearLayout i dodajemy trzy TextView s, każde z android:layout_margin z. Pojawia się następujący wynik:Zwijanie marginesów w układach Androida

actual result

Jednak chciałbym, aby uzyskać ten wynik:

expected result

wiem, że mogę to obejść ustawiając różne Górny/dolny margines dla różne pozycje:

  • ustawić górny margines pierwszego elementu i dolny margines ostatniego elementu na 10pkt.,
  • ustawić remainding Górny/dolny margines do 5DP,

ale sprawia, że ​​konstrukcja bardziej skomplikowana (zwłaszcza jeśli TextView są tworzone dynamicznie). Czy istnieje sposób na zachowanie marginesów jak w CSS? (Aby uzyskać wyjaśnienie, dlaczego ma to sens, zobacz: What is the point of CSS collapsing margins?)

Odpowiedz

14

To, co zwykle robię, aby to naprawić, to po prostu zmniejszyć margines widoku (tj. Twój tekst) o połowę i dodać ten sam numer, co margines do zawierającą ViewGroup (czyli twoją LinearLayout). W ten sposób otrzymasz równe odstępy wokół wszystkich przedmiotów. Na przykład:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:padding="5dip" 
    > 
    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dip" 
     android:text="I'm a TextView!" 
     /> 
    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dip" 
     android:text="I'm a TextView!" 
     /> 
    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dip" 
     android:text="I'm a TextView!" 
     /> 
</LinearLayout> 
Powiązane problemy