我想在我的安卓应用程序上实现一条 Toast 消息。 所以我在我的共享代码中创建了接口:
namespace TravelApp.Renderers
{
public interface IToast
{
void show(string message);
}
}
然后我在我的安卓项目上创建了接口实现
[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 文件中,我使用了煎饼视图,当我点击此视图时,我想显示我的吐司消息:
<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>
然后我在我的安卓项目中的 PlateformInitializer 类中注册我的容器:
namespace TravelApp.Droid
{
public class PlatformInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<IToast,Toast>();
}
}
}
我将其添加到 MainActivity 的应用程序构造函数中.cs :
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.com/docs/xamarin-forms/Dependency-Service.html
但是,当我运行代码并点击我的煎饼视图时,没有显示任何消息,我什至不确定该命令是否已触发......
我不知道我是否需要实现 IPlateformInitializer。
谢谢你的帮助,
这是我是如何做到的。
共享项目
public interface IToast
{
void LongAlert(string message);
void ShortAlert(string message);
}
安卓项目(渲染器( 您需要安装当前活动插件
[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);
}
}
在我的视图中的某个地方模型/共享项目中的任何地方
Helper.Toast("message here");