簡體   English   中英

如何使用interface使MainPage.xaml.cs與MainActivity.cs對話

[英]How to make MainPage.xaml.cs talk to MainActivity.cs using interface

我正在嘗試將這些類共享一些數據,我讀到正確的方法是通過接口,但MainPage.xaml.cs無法識別“鏈接”。 我需要在MainPage.xaml.cs中添加什么才能使其正常工作?

將Class1.cs:

namespace interfaceWebnav
{
    public interface IPortableInterface
    {
        object Test();
    }
}

MediaService.cs

using interfaceWebnav;

namespace ComprarMusicas
{
    public class MediaService : Java.Lang.Object, IPortableInterface
    {
        public object Test()
        {
            //do something
        }
    }
}

MainActivity.cs:

...
...
using interfaceWebnav;

[assembly: Dependency(typeof(IPortableInterface))]
namespace MyApp.Droid
{
     [Activity(Label = "Comprar Músicas", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, NoHistory = true,ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity :  global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ............
            base.OnCreate(savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
   }

    public override void OnBackPressed()
    {
        // here I need to know what SomeMethod() from MainPage.xaml.cs is saying
    }

}

MainPage.xaml.cs(我注釋了一些讓它工作的嘗試):

using Xamarin.Forms;
// using interfaceWebnav;

// [assembly: Dependency(typeof(IPortableInterface))]

namespace MyApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }

    void SomeMethod(object sender, EventArgs e)
    {
        object resultado = DependencyService.Get<IPortableInterface>().Test();
    }
}

在MainPage.xaml.cs上,visual studio講述了SomeMethod:“命名空間不能直接包含成員作為字段或方法。”

關於“Get IPortableInterface”它說:

“無法找到類型或命名空間IPortableInterface的名稱(您是否缺少using指令或程序集引用?)”

Add Class說你的android項目中的MediaService.cs從IPortableInterface繼承它

public class MediaService : Java.Lang.Object, IPortableInterface
{
    public void Test()
    {
        // your android platform specific implementation
    }

}

在MainPage.cs文件中調用依賴項服務

namespace MyApp
{
    public partial class MainPage : ContentPage
    {
        public bool foo = true; //just an example

        public MainPage()
        {
            InitializeComponent();
        }
    }
    //I suppose invoking any event lets says button click calling interface dependency service of android project
    void Button_Clicked(object sender,EventArgs e)
    {
        object resultado = DependencyService.Get<IPortableInterface>().Test();
    }

}

我希望這能幫到您

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM