xamarinxamarin.androidxamarin.formscustom-renderer

Xamarin forms Shadow on Frame in Android


The Frame class in Xamarin Forms is quite limited, and can't allow me to get a shadow behind the Frame. I've made a custom renderer for iOS using this code:

public class RatingInfoFrameRenderer : FrameRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
    {
        base.OnElementChanged(e);

        Layer.BorderColor = UIColor.White.CGColor;
        Layer.CornerRadius = 10;
        Layer.MasksToBounds = false;
        Layer.ShadowOffset = new CGSize(-2, 2);
        Layer.ShadowRadius = 5;
        Layer.ShadowOpacity = 0.4f;
    }
}

Making a similar one on Android is causing me problems, since my knowledge on Android native is kind of limited. Could anyone tell me what to look at, perhaps some good code example? I haven't found anything that looks similar to this.


Solution

  • It can be very easy in Android platform, but first of all, you need to create your shadow under Drawable folder of Android resources. For example, as shown in Android Developer Tips & Tricks by an anonymous contributor:

    <?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="#CABBBBBB" />
          <corners android:radius="2dp" />
        </shape>
      </item>
    
      <item
          android:left="0dp"
          android:right="0dp"
          android:top="0dp"
          android:bottom="2dp">
        <shape android:shape="rectangle">
          <solid android:color="@android:color/white" />
          <corners android:radius="2dp" />
        </shape>
      </item>
    </layer-list>
    

    Name this file as "shadow.xml" and place it under the Drawable folder of Android project, then in your RatingInfoFrameRenderer:

    public class RatingInfoFrameRenderer : FrameRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement != null)
            {
                ViewGroup.SetBackgroundResource(Resource.Drawable.shadow);
            }
        }
    }
    

    To change the style of shadow, you can modify the shadow.xml file, for more information about this, you may refer to google's official document: LayerList.