SoFunction
Updated on 2025-03-01

Sample code for adding shadow effects to layouts and controls on Android

Adding shadow effects to make the controls or layout look three-dimensional. In general, there are two solutions.

1. Directly use the attribute: android:elevation="4dp" code to achieve the effect. elevation represents the altitude, which is the height of the z-axis of the layout. Adjust the height, and you can choose the severity of the shadow.

<TextView 
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:elevation="4dp"
        android:background="@drawable/home_waitcourse_yellow_shape"
        android:textColor="@color/foorYellow"  
        android:text="Report"/>

2. This method requires writing some code, but not much, it is achieved by writing an XML.

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:andro > 

  <!-- Shadow part --> 
  <!-- Personally, I think it's more vivid:topRepresents the height of the shadow below,leftRepresents the shadow width on the right。Actually, it's the correspondingoffset,solidThe color in it is the color of the shadow,You can also set angles, etc. --> 
  <item 
    android:left="2dp" 
    android:top="2dp" 
    android:right="2dp" 
    android:bottom="2dp"> 
    <shape android:shape="rectangle" > 

      <gradient 
        android:angle="270" 
        android:endColor="#0F000000" 
        android:startColor="#0F000000" /> 

      <corners 
        android:bottomLeftRadius="6dip" 
        android:bottomRightRadius="6dip" 
        android:topLeftRadius="6dip" 
        android:topRightRadius="6dip" /> 
    </shape> 
  </item> 

  <!-- Background part --> 
  <!-- Expression of image:bottom代表Background part在上边缘超出阴影的高度,right代表Background part在左边超出阴影的宽度(Correspondingoffset) --> 
  <item 
    android:left="3dp" 
    android:top="3dp" 
    android:right="3dp" 
    android:bottom="5dp"> 
    <shape android:shape="rectangle" > 

      <gradient 
        android:angle="270" 
        android:endColor="#FFFFFF" 
        android:startColor="#FFFFFF" /> 

      <corners 
        android:bottomLeftRadius="6dip" 
        android:bottomRightRadius="6dip" 
        android:topLeftRadius="6dip" 
        android:topRightRadius="6dip" /> 
    </shape> 
  </item> 
</layer-list> 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.