具有左侧背景和渐变的Android可绘制对象

5
我们需要一个drawable,它在左边有大约10dp的背景和渐变色。实现效果如下图所示:
enter image description here
实现方法如下:
  1. 在左侧添加红色渐变
  2. 其余部分添加背景色
我可以使用layer-list并添加两个形状来尝试实现,但是没有成功。
这是需要实现的Item的背景:
<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>

你能更准确地解释一下你需要什么,如果你有期望的图片最好上传,这样会给我们更好的想象。 - androidqq6
我已经上传了一张图片,它会更清楚地解释它(希望如此;))。 - pixel
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>

输出图像:

enter image description here

更新:

你也可以这样做,将其左对齐并根据需要控制其大小,首先创建一个名为“side color.xml”的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>

输出图片:

在此输入图片描述

希望能帮到您。


我想要左对齐 - 在您的示例中,您已经将其硬编码为280dp。 - pixel
据我所知,这是我处理它的方式。 - Android Stack
但是如果我想让这个黑盒子半透明怎么办?那么我最终会在下面得到渐变效果... - pixel
确切地说 - 我希望它是半透明的。 - pixel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接