2011-12-16 50 views
1

上下文:我有一個基本上由一個RelativeLayout包裝一堆TextViews組成的小部件。這就是我想要的小工具,在視覺上看起來,其次是在XML佈局代碼:RelativeLayout:layout_marginLeft不一致的行爲

Expected layout

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/alarm_widget_layout" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    > 
    <TextView 
    android:id="@+id/alarm_time" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:text="8:30" 
    android:textSize="40sp" 
    /> 
    <TextView 
    android:id="@+id/alarm_am_pm" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_toRightOf="@id/alarm_time" 
    android:layout_marginLeft="2dp" 
    android:layout_alignTop="@id/alarm_time" 
    android:textSize="18sp" 
    android:text="AM" 
    /> 
    <TextView 
    android:id="@+id/alarm_days" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:layout_below="@id/alarm_time" 
    android:textSize="16sp" 
    android:text="M T W T F S S" 
    /> 
    <TextView 
    android:id="@+id/toggle_indicator" 
    android:layout_height="8sp" 
    android:layout_width="80sp" 
    android:layout_below="@id/alarm_days" 
    android:layout_centerHorizontal="true" 
    android:background="@drawable/toggle_button_oval" 
    /> 
</RelativeLayout> 

問:我難倒與layout_marginLeft在下列情況下不一致的行爲:

  1. 當這些小部件一個的LinearLayout中,AM/PM文本在右上方內垂直堆疊,需要機器人:layout_marginLeft =「15dp」看起來像它在畫面進行如上所述。
  2. 但是,當部件堆疊在2x2 TableLayout中時,AM/PM文本需要android:layout_marginLeft =「2dp」才能正確顯示。

爲什麼我看到這種不一致的行爲? layout_marginLeft使用什麼作爲「原點」?

回答

1

由於您使用的是垂直LinearLayout(orientation = vertical),因此android:layout_marginLeft會將屏幕的最左端作爲原點,因此需要較大的傾角值〜15。但是,如果您一直使用orientation = horizo​​ntal,則原點將是am_pm之前的元素的結尾,因此您需要較小的dip值〜2。 類似於相對錶格佈局的情況。由於在使用RelativeLayout時,您提到了android:layout_toRightOf =「@ id/alarm_time」,原點將是alarm_time的結尾,因此需要較小的傾角值。

+0

感謝您的回覆@SaurabhVerma。我不確定我是否正確理解這一點。你是說layout_marginLeft使用的原點是基於RelativeLayout的堆疊方式嗎?如果RelativeLayout堆疊在垂直LinearLayout中,則原點位於屏幕的最左側。但是,如果將其堆疊在2x2 TableLayout中,則原點是@ id/alarm_time(由於layout_toRightOf屬性)。這非常令人困惑!這種行爲是否在任何地方記錄? – 2011-12-16 10:31:24