c# - 如何使用接口使 MainPage.xaml.cs 与 MainActivity.cs 对话
问题描述
我正在尝试让这些类共享一些数据,我读到正确的方法是通过接口但 MainPage.xaml.cs 无法识别“链接”。我需要在 MainPage.xaml.cs 中添加什么才能使其工作?
Class1.cs:
namespace interfaceWebnav
{
public interface IPortableInterface
{
object Test();
}
}
媒体服务.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:“命名空间不能直接包含成员作为字段或方法。”
关于“获取 IPortableInterface”它说:
“找不到类型或命名空间 IPortableInterface 的名称(您是否缺少 using 指令或程序集引用?)”
解决方案
在你的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();
}
}
我希望这能帮到您
推荐阅读
- c - 指针非法访问 PIC32 上的数组
- java - 如何使用 CardLayout 将 JPanel 从另一个类添加到面板?
- swagger-ui - 如何在 OpenAPI 3.0 中记录 RFC3339 日期时间输入?
- reactjs - 无法设置状态以响应字符串数组
- typescript - 尽管声称 Prettier 不支持私有方法
- angular6 - angular6不刷新css更改
- git - “与您的容器共享 Git 凭据”不起作用
- jenkins - Jenkins 声明式管道 ssh 代理插件
- mysql - NodeJS Mysql pool.query() 没有释放连接?
- python - Django Auth Group 拒绝更改 UpdateViews