2014-07-16 57 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的详细信息。