首页 文章

如何在Xamarin.forms中使用Float Action Button与PCL项目表单代码共享?

提问于
浏览
0

我是Xamarin,Xamarin.Forms和C#平台的新手 .

我正在使用这些技术进行一些实验,现在我正在搜索如何在Xamarin.Forms中使用平台特定的UI组件与PCL项目进行代码共享 .

在网上搜索我发现了FAB按钮的一些实现(example),但这些实现已被弃用或放弃 .

我知道有可能Embed Native Controls into Xamarin.Forms,但这种方法使用SAP项目......

My question is: 有没有办法将FAB按钮(或其他一些特定于平台的UI控件)用于带有PCL项目的Xamarin.Forms解决方案以进行代码共享?如果是,那么其他平台的行为是什么?我希望iOS UI上不显示FAB按钮 .

谢谢您的帮助 .

1 回答

  • 1

    我不会在这里建议任何第三方库,但通常我们可以使用Custom Renderers从PCL使用目标平台的本机控件 .

    对于FloatingActionButton的Android平台,您可以尝试实现视图渲染器 .

    例如,在PCL中创建一个名为 MyFloatButton 的类:

    public class MyFloatButton : View
    {
    }
    

    然后在android项目中创建另一个名为 MyFloatButtonRenderer 的类,例如:

    [assembly: ExportRenderer(typeof(MyFloatButton), typeof(MyFloatButtonRenderer))]
    
    namespace NameSpace.Droid
    {
        public class MyFloatButtonRenderer : Xamarin.Forms.Platform.Android.ViewRenderer<MyFloatButton, FloatingActionButton>
        {
            private FloatingActionButton fab;
    
            protected override void OnElementChanged(ElementChangedEventArgs<MyFloatButton> e)
            {
                base.OnElementChanged(e);
    
                if (Control == null)
                {
                    fab = new FloatingActionButton(Xamarin.Forms.Forms.Context);
                    fab.LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
                    fab.Clickable = true;
                    fab.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.icon));
                    SetNativeControl(fab);
                }
    
                if (e.NewElement != null)
                {
                    fab.Click += Fab_Click;
                }
    
                if (e.OldElement != null)
                {
                    fab.Click -= Fab_Click;
                }
            }
    
            private void Fab_Click(object sender, EventArgs e)
            {
            }
        }
    }
    

    我希望iOS UI上不显示FAB按钮 .

    如果您只想为Android平台显示此控件,您可以在页面的PCL xaml中进行编码,例如:

    <OnPlatform x:TypeArguments="View">
        <OnPlatform.Android>
            <local:MyFloatButton WidthRequest="50" HeightRequest="50" HorizontalOptions="Center" />
        </OnPlatform.Android>
        <OnPlatform.iOS>
            <!--use other view here-->
        </OnPlatform.iOS>
    </OnPlatform>
    

    或者您可以检查在代码后面添加此控件,请查看此博客:Embedding Native Controls into Xamarin.Forms

相关问题