2014-07-16 59 views
2

我有一個相對的佈局,佔用全屏幕和白色背景。 (fill_parent已設置) 我需要在左側和右側留有餘量。邊緣區域應具有不同的背景顏色。 如何設置邊緣區域的背景顏色?android margin爲不同背景顏色的相對佈局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/c1_cnxlayout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_marginLeft="50dp" 
    android:layout_marginRight="50dp" 
    android:background="@color/purewhite" > 

回答

4

添加另一個RelativeLayout在裏面,設置兩個不同的背景顏色

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/c1_cnxlayout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@color/color1" > 

    <RelativeLayout 
     android:id="@+id/c2_cnxlayout" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_marginLeft="50dp" 
     android:layout_marginRight="50dp" 
     android:background="@color/color2" /> 

</RelativeLayout> 
+0

但是,這種方法有效,但嵌套佈局容器通常比使用單個佈局容器使用更多的系統內存。 – Nicks

+0

@Nicks是的,這可能會導致一些性能問題,但這似乎是唯一的方法。我不認爲多一層'RelativeLayout'會導致很多麻煩。你可能有更優雅的方式? – Wesley

+0

我同意,對於小型項目和性能來說,它絕對是更簡單的解決方案,也不會在嵌套一個級別時受到影響。 :-) – Nicks

1

任何一種邊界,任何佈局可以通過形狀繪製對象來實現。 在相對佈局頁邊距的情況下可以完成: -

在可繪製文件夾中創建一個margin.xml文件。我在代碼中添加了註釋。

<?xml version="1.0" encoding="utf-8"?> 
<!--By default the border shape is rectangle, can be changed using android:shape--> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 

    <!-- This wil be the views background color, where this margin.xml is applied --> 
    <solid android:color="@color/view_bg"></solid> 

    <!-- Border color and its width is defined by stroke --> 
    <stroke 
     android:width="5dp" 
     android:color="@color/border_blue"></stroke> 

    <!-- The radius makes the corners rounded --> 
    <corners android:radius="10dp"></corners> 
    <!--represents the variation of color intensity in a direction represented by angle--> 
    <gradient 
     android:angle="45" 
     android:endColor="@color/gradient_end" 
     android:startColor="@color/gradient_start" /> 
</shape> 

和價值文件夾添加這colors.xml文件

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="view_bg">#b20e0f</color> 
    <color name="white">#ffffff</color> 
    <color name="btn_bg">#3e4a56</color> 
    <color name="border_blue">#1A237E</color> 
    <color name="gradient_start">#FFFF0000</color> 
    <color name="gradient_end">#80FF00FF</color> 
</resources> 

終於在你的RelativeLayout標記補充一點: -

android:background="@drawable/margin" 

參考this link的詳細信息。