[英]How to use @Subscribe annotation on Xamarin.Forms Android platform using Greenrobot.EventBus package
我正在嘗試在 Xamarin 上實現 EventBus,但無法訂閱事件,因為當我添加注釋 @Subscribe() 時,出現錯誤“@Subscribe 在當前上下文中不存在”。 當我在沒有@Subscribe 注釋的情況下運行應用程序時,它向我顯示一個錯誤,說“MainActivity 及其超類沒有帶有@Subscribe 注釋的公共方法”。 請幫助我了解如何在 Xamarin Android 平台上訂閱活動
#MainActivity class:
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
//Registering Event Bus here
EventBus.Default.Register(this);
SetContentView(Resource.Layout.activity_main);
}
@Subscribe //Showing me an error while adding this annotation
public void OnEvent(NetworkInfo networkInfo)
{
Console.WriteLine(networkInfo);
}
protected void OnDestroy()
{
base.OnDestroy();
EventBus.Default.Unregister(this);
}
}
PublisherEvent class:
public class PublishEvent
{
public PublishEvent()
{
EventBus.getDefault().post(message);
}
}
我不確定 Xamarin Forms 是否支持EventBus ,並使用@Subscribe()
與原生 Android 相同。
但是,在 Xamarin Forms 中有相同的方法。 您可以使用Xamarin.Forms MessagingCenter來實現,它還可以訂閱消息和接收消息。
發送消息:
MessagingCenter.Send<object>(this, "Hi");
訂閱留言:
MessagingCenter.Subscribe<object> (this, "Hi", (sender) =>
{
// Do something whenever the "Hi" message is received
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.