2020.09.01.

Xamarin.Android – Shadow

By bence960206

In Android you can’t set shadow property of an element except Button and TextView. So we have to define a shape in an xml and set is as background of an element.

Let’s create our first shadow background! Create a shadow.xml file in the Resource/drawable folder, and paste this code in the file.

<?xml version="1.0" encoding="utf-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle"
           android:alpha="0.2">
      <solid android:color="#F4F4F7"/>
      <corners android:radius="11dp"/>
    </shape>
  </item>
  <item
      android:left="0dp"
      android:right="0dp"
      android:top="0dp"
      android:bottom="0dp">
    <shape android:shape="rectangle">
      <solid android:color="#fff"/>
      <corners android:radius="11dp"/>
    </shape>
  </item>
</layer-list>

After that, we have to set this drawable as the background of a LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <LinearLayout
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:gravity="center"
        android:elevation="30dp"
        android:background="@drawable/shadow">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:text="Some text"/>
    </LinearLayout>
</LinearLayout>

We have to set the android:elevation property of the LinearLayout. (Elevation is the relative distance between two surfaces along the z-axis.) The larger the elevation value, the larger the shadow radius will be.

And that’s all, we have a LinearLayout in the middle of the page and it has shadow and in this LinearLayout we have a TextView.