![](/img/trans.png)
[英]Sharing code in a Xamarin project across .NET Core and Xamarin.Forms
[英]How to use a Float Action Button in Xamarin.forms with a PCL project form code sharing?
我是Xamarin,Xamarin.Forms和C#平台的新手。
我正在使用这些技术进行一些实验,现在我正在搜索如何在Xamarin.Forms中将特定于平台的UI组件与PCL项目一起使用以进行代码共享。
在网上搜索时,我发现了FAB按钮的一些实现( 例如 ),但是这些实现已被弃用或放弃。
我知道可以将本机控件嵌入Xamarin.Forms中 ,但是这种方法使用SAP项目...
我的问题是:是否可以将FAB按钮(或某些其他特定于平台的UI控件)用于带有PCL项目的Xamarin.Forms解决方案中以进行代码共享? 如果是,其他平台的行为将如何? 我希望FAB按钮不会出现在iOS UI上。
谢谢您的帮助。
我在这里不建议任何第三方库,但是通常我们可以使用自定义渲染器来使用PCL中目标平台的本机控件。
对于Android平台的FloatingActionButton ,您可以尝试实现视图渲染器。
例如,在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)
{
}
}
}
我希望FAB按钮不会出现在iOS UI上。
如果只希望将此控件显示在Android平台上,则可以在页面的xml PCL中进行编码,例如:
<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>
或者,您可以在后面的代码中添加此控件,请查看此博客:将本机控件嵌入Xamarin.Forms
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.