5

W想要一个drawable在左边有背景和渐变的,大约是10dp宽的。

我想要实现的图像:

在此处输入图像描述

  1. 左边的红色渐变
  2. 其余的背景

我怎样才能做到这一点?

我试过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>
4

1 回答 1

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> 

输出图像:

在此处输入图像描述

您还可以将红色 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>

输出图像:

在此处输入图像描述

更新:

您也可以通过这种方式将其对齐到左侧,也可以根据需要控制其大小,

首先创建一个 XML 并将其命名为 side 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>

输出图像:

在此处输入图像描述

希望对您有所帮助。

于 2012-11-27T22:23:49.803 回答