我想在我的Android应用程序上实现一个Toast消息.所以我在我的共享代码中创建了接口。
namespace TravelApp.Renderers
{
public interface IToast
{
void show(string message);
}
}
然后我在我的Android项目中创建了接口实现。
[assembly:Dependency(typeof(TravelApp.Droid.Toast))]
namespace TravelApp.Droid
{
public class Toast : IToast
{
public void show(string message)
{
Android.Widget.Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short).Show();
}
}
}
在我的XAML文件中我使用了一个pancakeview,当我点击这个视图时,我想显示我的吐司信息。
<pancake:PancakeView x:Name="MyPancakecs" HorizontalOptions="EndAndExpand"
VerticalOptions="EndAndExpand"
CornerRadius="60"
HeightRequest="50"
WidthRequest="50"
BackgroundColor="{StaticResource BackgroundColor}"
Margin="0,0,60,0"
Padding="15"
>
<Image Source="TrayPlus"></Image>
<pancake:PancakeView.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ToastMyToaster}"/>
</pancake:PancakeView.GestureRecognizers>
</pancake:PancakeView>
然后我在我的android项目中的PlateformInitializer类中注册我的容器。
namespace TravelApp.Droid
{
public class PlatformInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<IToast,Toast>();
}
}
}
我在MainActivity.cs的App构造函数中添加了它。
LoadApplication(new App(new PlatformInitializer())) ;
然后在我的ViewModel中,我在构造函数中添加了一个IToast对象。
namespace TravelApp.ViewModels
{
public class TravelListViewModel : BindableBase
{
private string _messageToast;
public string MessageToast
{
get { return _messageToast; }
set { SetProperty(ref _messageToast, value); }
}
public DelegateCommand ToastMyToaster;
public TravelListViewModel(INavigationService navigationService, ITravelRepository travelRepository, IToast Toaster)
{
this._navigationService = navigationService;
this._travelRepository = travelRepository;
this._messageToast = "Test Toaster";
this._toaster = Toaster;
this.ToastMyToaster = new DelegateCommand(ToastShow);
}
private void ToastShow()
{
this._toaster.show(MessageToast);
}
}
在我的研究中,我使用了这个文档。https:/prismlibrary.comdocsxamarin-formsDependency-Service.html。
但是当我运行这段代码并点击我的pancakeview时,没有任何信息显示,我甚至不确定命令是否被触发......
我不知道我是否需要实现IPlateformInitializer。
谢谢您的帮助。
下面是我的做法。
共享项目
public interface IToast
{
void LongAlert(string message);
void ShortAlert(string message);
}
Android项目(渲染器)你需要安装 当前活动插件
[assembly: Dependency(typeof(AndroidToast))]
namespace yournamespace
{
public class AndroidToast : IToast
{
public void LongAlert(string message)
{
Toast.MakeText(CrossCurrentActivity.Current.Activity, message, ToastLength.Long).Show();
}
public void ShortAlert(string message)
{
Toast.MakeText(CrossCurrentActivity.Current.Activity, message, ToastLength.Short).Show();
}
}
}
在我的共享项目中调用敬酒
internal static void Toast(string message, bool isShort=false)
{
var toast = DependencyService.Get<IToast>();
if (toast != null)
{
if (!isShort)
toast.LongAlert(message);
else
toast.ShortAlert(message);
}
}
在我看来Model在共享项目中的任何地方。
Helper.Toast("message here");