Android可绘制的背景和左侧的渐变

时间:2012-11-27 19:45:29

标签: android drawable gradient shape

W希望有一个drawable左边的背景和渐变,大约10dp宽。

我想要实现的目标:

enter image description here

  1. 左侧的红色渐变
  2. 其余的背景
  3. 我如何实现这一目标?

    我尝试了layer-list有两种形状,但没有运气。

    项目背景:

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:drawable="@drawable/background" />
        <item android:drawable="@drawable/gradient" />
    </layer-list>
    

    背景可绘制:

    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <solid android:color="@color/black" />
    </shape>
    

    形状可绘制:

    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
        <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
            android:angle="90"/>
           <size android:width="10dp" />
    </shape>
    

1 个答案:

答案 0 :(得分:8)

在drawable文件夹中创建 sidecolor (或任何您想要的名称) XML ,如下所示:

  <?xml version="1.0" encoding="utf-8"?>
  <layer-list xmlns:android="http://schemas.android.com/apk/res/android">  
    <item android:drawable="@drawable/background" android:bottom="5dp"
        android:top="5dp"  android:left="5dp" android:right="5dp"/>  
    <item android:drawable="@drawable/red" android:bottom="5dp"  android:top="5dp"
        android:left="5dp" android:right="280dp" /> 
  </layer-list> 

然后创建后台XML:

 <?xml version="1.0" encoding="utf-8"?>
   <shape xmlns:android="http://schemas.android.com/apk/res/android"
               android:shape="rectangle">
        <solid android:color="@android:color/black" />    
   </shape>

然后将红色XML作为形状:

  <?xml version="1.0" encoding="utf-8"?>
   <shape xmlns:android="http://schemas.android.com/apk/res/android"  
         android:shape="rectangle">       
      <solid android:color="#B22222" /> 
  </shape> 

输出图像:

enter image description here

您也可以将红色XML创建为渐变:

 <?xml version="1.0" encoding="utf-8" ?> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android"  
            android:shape="rectangle">
      <gradient android:startColor="#B22222" android:centerColor="#FFFFFF" 
           android:endColor="#B22222" android:angle="0" /> 
     </shape>

输出图像:

enter image description here

<强>更新

也可以这样做,将它对齐到左边也可以根据需要控制它的大小,

首先创建一个XML并将其命名为color.xml,并通过以下方式引用视图:

android:background="@drawable/sidecolor"

sidecolor.xml:

  <?xml version="1.0" encoding="utf-8" ?>    
     <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

   <item>
        <shape android:shape="rectangle">
             <solid android:color="#FF0000" />        
       </shape>    
  </item>

  <item android:left="10dp">
       <shape android:shape="rectangle">
            <solid android:color="#000000" />
       </shape>
  </item>
     </layer-list>

输出图像:

enter image description here

希望帮助你。