hellaandrew hellaandrew - 4 months ago 65x
Android Question

Why can't I set the elevation on a view that I add programmatically?

Disclaimer: I am using Xamarin.Android.

I created a view, set its elevation, and then add it to my main layout. The view successfully gets added to the layout when I trigger the event, but there is no elevation shadow whatsoever.

Here is what I am working with:

View that gets added programmatically:

public class TooltipTest : FrameLayout
private Context context;
private ShapeDrawable box;
private View carrot;
private string message;

public TextView TooltipText
private set;

public TooltipTest(Context context, string message) : base(context)
this.context = context;
this.message = message;


private void Initialize()

private void CreateText()
int paddingTopBottom = 30;
int paddingLeftRight = 27;

TooltipText = new TextView(context);
TooltipText.Text = message;
TooltipText.SetTextColor(new Color(ContextCompat.GetColor(context, Resource.Color.tooltipText)));
TooltipText.SetTextSize(ComplexUnitType.Sp, 14f);
TooltipText.SetPadding(paddingLeftRight, paddingTopBottom, paddingLeftRight, paddingTopBottom);
TooltipText.SetBackgroundColor(new Color(ContextCompat.GetColor(context, Resource.Color.tooltipBackground)));


Event to add the view:

ButtonTest.Click += (sender, e) => {
var tooltip = new TooltipTest(this, Resources.GetString(Resource.String.test_text));
var tooltipParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
tooltip.Elevation = 20f;
ParentLayout.AddView(tooltip, tooltipParams);

Any ideas on why the shadow doesn't show? I've tried setting SetClipToPadding(false) and SetClipChildren(false) on the
, but that had no effect.


Use the AppCompat method ViewCompat.SetElevation(View, int) to set the elevation as desired. But on a pre-Lollipop devices, the method appears to do nothing. The only way I found to render shadows to pre-Lollipop UI elements was using a background instead:


If you want do dig more on this topic, go to this reddit topic and search for elevation. There are really good updated information there.