自定义Android视图不显示在Xamarin相对布局中

时间:2017-01-17 16:10:51

标签: xamarin xamarin.forms

我有一个简单的Xamarin Forms内容页面,如下所示

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              xmlns:local="clr-namespace:MyCustomView"
            x:Class="MyCustomView.MyContentPage">
  <ContentPage.Content>
    <RelativeLayout>
    <local:CustomView 
                                RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Constant=0, Factor=0}"
                                RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Constant=0, Factor=0}"/>
    </RelativeLayout>
  </ContentPage.Content>
</ContentPage>

local:CustomView定义为

public class CustomView : ContentView
{
    public CustomView()
    {

    }
}

我为此创建了以下自定义渲染器

[assembly: Xamarin.Forms.ExportRenderer(typeof(MyCustomView.CustomView), typeof(MyCustomView.Droid.CustomViewRendererDroid))]
namespace MyCustomView.Droid
{
    public class CustomViewRendererDroid : ViewRenderer<MyCustomView.CustomView, View>
    {
        View _backgroundView;

        protected override void OnElementChanged(ElementChangedEventArgs<CustomView> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement != null && Control == null)
            {
                _backgroundView = new View(this.Context);
                _backgroundView.LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
                _backgroundView.SetBackgroundColor(Color.Blue);
                _backgroundView.BringToFront();
                _backgroundView.SetMinimumHeight(100);
                _backgroundView.SetMinimumWidth(100);
                _backgroundView.Left = 50;
                _backgroundView.Top = 100;
                SetWillNotDraw(false);
                SetNativeControl(_backgroundView);
            }

        }
    }
}

无论我尝试什么(因此在渲染器中有很多定位,着色等),我都无法将此自定义视图显示在RelativeLayout中,但如果我将XAML更改为使用StackLayout,则看起来没问题。我错过了什么?

0 个答案:

没有答案