找不到Xamarin.Forms.Platform.Android.LabelRenderer(xamarin表单)的构造函数

当我在我的samsumg galaxy s5设备中测试我的应用程序时,我在pcl项目的xaml中有一个图像列表我这样做:我进入列表的页面,然后我按下操作栏上的后退按钮…我做了很多次……然后,它发生了:

System.NotSupportedException:无法从本机句柄0x20e0001d(key_handle 0x42433c30)激活Xamarin.Forms.Platform.Android.Platform + DefaultRenderer类型的实例。

要么

无法从本机激活Xamarin.Forms.Platform.Android.LabelRenderer类型的实例


更新

我添加了这个脚本:

using System; using Android.Runtime; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(Xamarin.Forms.Label), typeof(LabelRenderer))] namespace neoFly_Montana.Droid { ///  /// This renderer was added to resolve a bug that crashed the application in known case /// Bug 36285 - Android App (Always) Crashes After Navigating Away From Page With A ScrollView In HeaderTemplate of ListView ///  /// and /// Bug 32462 - Crash after a page disappeared if a ScrollView is in the HeaderTemplate property of a ListView ///  ///  public class LabelRenderer : Xamarin.Forms.Platform.Android.LabelRenderer { public LabelRenderer() { } public LabelRenderer(IntPtr javaReference, JniHandleOwnership transfer): base() { } } } 

错误仍在这里

————————————–更新

然后,我改变了,现在我的代码是:

 using System; using Android.Runtime; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using neoFly_Montana.Droid; using Android.Content; [assembly: ExportRenderer(typeof(Xamarin.Forms.Label), typeof(NeoFly_MontanaLabelRenderer))] namespace neoFly_Montana.Droid { public class NeoFly_MontanaLabelRenderer : Xamarin.Forms.Platform.Android.LabelRenderer { public NeoFly_MontanaLabelRenderer(Context context) : base(context) { } } } 

那么,我经常可以看到这个错误。

System.NotSupportedException:无法从本机句柄激活neoFly_Montana.Droid.NeoFly_MontanaLabelRenderer类型的实例

当我按下顶部栏上的后退按钮时运行的页面,并且出现错误XAML (PCL):

                

C#的那个

 using FFImageLoading; using FFImageLoading.Forms; using neoFly_Montana.Api; using neoFly_Montana.Model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace neoFly_Montana.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ProdutosView : ContentPage { List lstProdutos = new List(); Categorias categEscolhida; public Color FundoColor { get { return fundoColor; } } public Color TextColor { get { return textColor; } } Color fundoColor; Color textColor; string lojaProx; string codLoja; public ProdutosView(string codLoja, Object categEscolhida, object produtos, string lojaProx) { this.codLoja = codLoja; this.categEscolhida = new Categorias(); this.categEscolhida = (Categorias)categEscolhida; lstProdutos = (List)produtos; fundoColor = Color.FromHex(this.categEscolhida.corFundo); textColor = Color.FromHex(this.categEscolhida.corTexto); this.Title = this.categEscolhida.nome; //TrataImagens(); InitializeComponent(); if (lojaProx != null) { this.lojaProx = lojaProx; prod_lbl_lojaprox.Text = lojaProx; } PopulaListView(); //if (Device.OS == TargetPlatform.iOS) //{ // this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0); //} } void TrataImagens() { foreach (var item in lstProdutos) { if (item.imagem != null && item.imagem.Trim() != "") { int initIndex = item.imagem.IndexOf(','); string u = item.imagem.Substring(initIndex+1); try { var bytes= Convert.FromBase64String(item.imagem); item.imagem = System.Text.Encoding.Unicode.GetString(bytes, 0, bytes.Length); // item.imagem = Encoding.UTF8.GetString(bytes); } catch (Exception e) { var ss = e.Message; } } } } private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e) { var list = (ListView)sender; list.SelectedItem = null; } void PopulaListView() { int row = 0; int column = 0; Grid grid_acompanhamentos = new Grid { // BackgroundColor = Color.Red, RowSpacing = 0, Padding = new Thickness(0, 0, 0, 0), HorizontalOptions = LayoutOptions.CenterAndExpand, Margin = new Thickness(10, 10, 10, 10), ColumnSpacing = 0, }; //CachedImage prod_acomp_img = new CachedImage //{ // Source = "texturaCateg.png", // Aspect = Aspect.Fill, // BackgroundColor = Color.FromHex(this.categEscolhida.corFundo) //}; //produtos listview_produtos.ItemsSource = lstProdutos; //observação if (categEscolhida.observacao != null && categEscolhida.observacao.Trim() != "") { label_observ.Text = categEscolhida.observacao; prod_stack_obser.IsVisible = true; lapis.IsVisible = true; } //acompanhamentos if (categEscolhida.acompanhamentos == null || categEscolhida.acompanhamentos.Count() == 0) { stack_acompanhamentos.IsVisible = false; } else { //prod_acompanhamentos_title.BackgroundColor = fundoColor; prod_acomp_img.BackgroundColor = fundoColor; produtos_acomp_title.TextColor = textColor; foreach (var item in categEscolhida.acompanhamentos) { StackLayout stack = new StackLayout(); stack.Margin = new Thickness (0,10,0,10); stack.HorizontalOptions = LayoutOptions.StartAndExpand; //stack.BackgroundColor = Color.Orange; stack.Spacing = 0; stack.Children.Add(new Label { Text = item.nome, HorizontalTextAlignment = TextAlignment.Start, TextColor = textColor, HorizontalOptions=LayoutOptions.Start, FontAttributes = FontAttributes.Bold, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) }); if (item.observacao != null) stack.Children.Add(new Label { Text = item.observacao, HorizontalTextAlignment = TextAlignment.Start, HorizontalOptions = LayoutOptions.Start, TextColor = textColor, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) }); else stack.Children.Add(new Label { Text = " ", TextColor = textColor, HorizontalTextAlignment = TextAlignment.Start, HorizontalOptions = LayoutOptions.Start, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) }); grid_acompanhamentos.Children.Add(stack, column, row); if (column == 0) { column = 1; } else { column = 0; row++; } } stack_acompanhamentos.Children.Add(grid_acompanhamentos); //produtos_rl_acompanhamentos.Children.Add(grid_acompanhamentos, // Constraint.RelativeToParent((parent) => // { // return (parent.Width / 2) - (grid_acompanhamentos.Width / 2); // }), // Constraint.RelativeToParent((parent) => // { // return (parent.Height / 2) - (grid_acompanhamentos.Height / 2); // }) //); //produtos_rl_acompanhamentos.Children.Add(prod_acomp_img, Constraint.RelativeToParent((parent) => { // return parent.X; //}), Constraint.RelativeToParent((parent) => { // return parent.Y; //}), Constraint.RelativeToParent((parent) => { // return parent.Width; //}), Constraint.RelativeToView(grid_acompanhamentos, (parent, sibling) => { // var teste = sibling.Height; // return teste; //})); //UpdateConstraintsBasedOnWidth(produtos_rl_acompanhamentos, grid_acompanhamentos); // produtos_rl_acompanhamentos.RaiseChild(grid_acompanhamentos); } } public static void UpdateConstraintsBasedOnWidth(Xamarin.Forms.RelativeLayout layout, Xamarin.Forms.View view) { view.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) => { if (e.PropertyName == "Width") { layout.ForceLayout(); } }; view.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) => { if (e.PropertyName == "Height") { layout.ForceLayout(); } }; } } } 

上一页上面的页面应该在错误发生时回到XAML (PCL)

                      

代码背后

 using FFImageLoading.Forms; using neoFly_Montana.Api; using neoFly_Montana.Model; using neoFly_Montana.PopUp; using Rg.Plugins.Popup.Services; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace neoFly_Montana.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CategoriasView : ContentPage { ActivityIndicator indicator; string codigoLoja; List lstCategorias; List lstProdutos = new List(); List lstAcompanhamentos; Categorias categoriaEscolhida; string observacao; string codCategoria; string lojaProx; LoadingPopUp loading; public CategoriasView(string codigoLoja, string lojaProx, object lstCategorias) { this.codigoLoja = codigoLoja; this.lojaProx = lojaProx; //this.codigoLoja = "162"; this.lstCategorias = (List)lstCategorias; InitializeComponent(); categorias_lbl_ljproxima.Text = lojaProx; CriaTela(); } void CriaLoading() { LoadingPopUp loading = new LoadingPopUp("Carregando...", Color.Brown); PopupNavigation.PushAsync(loading, false); } private void CriaTela() { int row = 0; int column = 0; gridtextura.RowSpacing = 5; gridtextura.ColumnSpacing = 15; lstCategorias = lstCategorias.OrderBy(o => o.nome).ToList(); foreach (var item in lstCategorias) { Grid GridContent = new Grid { RowSpacing = 0, Margin = new Thickness(0, 5, 0, 0), VerticalOptions = LayoutOptions.FillAndExpand, RowDefinitions = { new RowDefinition { Height = new GridLength(8, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(2, GridUnitType.Star) } } }; var textura = new CachedImage(); textura.Source = "texturaCateg"; textura.HorizontalOptions = LayoutOptions.FillAndExpand; textura.VerticalOptions = LayoutOptions.FillAndExpand; textura.Aspect = Aspect.Fill; GridContent.BindingContext = item; Grid boxColorView = new Grid { RowSpacing = 0, //InputTransparent = true, VerticalOptions = LayoutOptions.FillAndExpand, RowDefinitions = { new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(8, GridUnitType.Star) } } }; boxColorView.Children.Add(new StackLayout { BackgroundColor = Color.FromHex(item.corFundo), VerticalOptions = LayoutOptions.FillAndExpand }, 0, 1); boxColorView.Children.Add(textura, 0, 1); // boxColorView.Children.Add(new BoxView { VerticalOptions = LayoutOptions.FillAndExpand }, 0, 0); gridtextura.Children.Add(boxColorView, column, row); gridtextura.Children.Add(GridContent, column, row); //Qual categoria foi escolhida? var CliqueCategoria = new TapGestureRecognizer(); CliqueCategoria.NumberOfTapsRequired = 1; CliqueCategoria.Tapped += (s, e) => { CriaLoading(); var stacklayout = s as Grid; categoriaEscolhida = (Categorias)stacklayout.BindingContext; ChamaProdutos(); }; GridContent.GestureRecognizers.Add(CliqueCategoria); if (item.imagem != null && item.imagem != "") { int initIndex = item.imagem.IndexOf(','); string image = ""; image = item.imagem.Substring(initIndex + 1); try { GridContent.Children.Add(new CachedImage { Source = ImageSource.FromStream(() => new MemoryStream(Convert.FromBase64String(image))), VerticalOptions = LayoutOptions.FillAndExpand, DownsampleHeight = 60 }, 0, 0); } catch (Exception e) { GridContent.Children.Add(new CachedImage { Source = "error.png", VerticalOptions = LayoutOptions.FillAndExpand, DownsampleHeight = 50, HorizontalOptions = LayoutOptions.Fill, HeightRequest = 50, WidthRequest = 50 }, 0, 0); } } GridContent.Children.Add(new Label { Text = item.nome, TextColor = Color.FromHex(item.corTexto), FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), FontAttributes = FontAttributes.Bold, HorizontalTextAlignment = TextAlignment.Center, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.CenterAndExpand, LineBreakMode = LineBreakMode.TailTruncation }, 0, 1); if (column == 0) { column = 1; } else { column = 0; row++; } } } async Task ChamaProdutos() { await CallingProdutosAsync(); await CallingAcompanhamentosAsync(); await Navigation.PushAsync(new Views.ProdutosView(codigoLoja, categoriaEscolhida, lstProdutos, lojaProx), true); PopupNavigation.PopAsync(); if (lstProdutos == null) DisplayAlert("Ops", "Verifique sua conexão com a internet e tente novamente.", "Ok"); } //carregamento de dados para a tela de produtos async Task CallingProdutosAsync() { lstProdutos = await Webservice.GetProdutosAsync(codigoLoja, categoriaEscolhida.idCategoria); } //este pode estar zerado async Task CallingAcompanhamentosAsync() { categoriaEscolhida.acompanhamentos = new List(); categoriaEscolhida.acompanhamentos = await Webservice.GetAcompanhamentoAsync(codigoLoja, categoriaEscolhida.idCategoria); } } } 

—————– update ————现在,似乎标签渲染器错误不再发生……但默认情况下+渲染器错误仍然在这里…以及一个空引用exception(我认为它与我的标签渲染器代码中的构造函数有关)

您已经命名了类LabelRenderer ,它已经存在于Xamarin.Forms.Platform.Android命名空间中。

在assembly属性中, typeof(LabelRenderer)等同于typeof(Xamarin.Forms.Platform.Android.LabelRenderer) ,但我们需要它是typeof(neoFly_Montana.Droid.LabelRenderer)

避免这些命名空间冲突的简单方法是使用唯一的类名,如NeoFly_MontanaLabelRenderer

当使用Xamarin.Forms v2.5 +时,我们需要使用重载的构造函数,我在下面添加了它。

对于Xamarin.Forms v2.4(及以下)

 using System; using Android.Runtime; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using neoFly_Montana.Droid; [assembly: ExportRenderer(typeof(Xamarin.Forms.Label), typeof(NeoFly_MontanaLabelRenderer))] namespace neoFly_Montana.Droid { public class NeoFly_MontanaLabelRenderer : Xamarin.Forms.Platform.Android.LabelRenderer { } } 

对于Xamarin.Forms v2.5 +

 using System; using Android.Runtime; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using neoFly_Montana.Droid; [assembly: ExportRenderer(typeof(Xamarin.Forms.Label), typeof(NeoFly_MontanaLabelRenderer))] namespace neoFly_Montana.Droid { public class NeoFly_MontanaLabelRenderer : Xamarin.Forms.Platform.Android.LabelRenderer { public NeoFly_MontanaLabelRenderer(Context context) : base(context) { } } }