c# - Xamarin C# 无法将 c# 类转换为 Android.content.context

标签 c# android xamarin.android

我正在尝试通过在我按下我在共享代码项目中创建的按钮时显示来自 android 项目的警告对话框来测试我的应用程序的 DependencyService。

当我尝试通过在括号中输入“this”来设置“AlertDialog.Builder”中的上下文属性时,出现此错误:“无法从‘CallDiverter2.Droid.CallDiverter_Android’转换为‘Android.Content.Context’ .

命名空间还装饰有:'[assembly: Dependency(typeof(CallDiverter_Android))]' 如果它很重要。

这是我想使用 DependecyService 调用的 android 项目中的函数:

public class CallDiverter_Android : ICallDiverter
{
    public void DivertCall(string callForwardString)
    {
        //Divert call code

        //String callForwardString = "**21*1234567890#";
        //Intent callIntent = new Intent(Intent.ActionDial); // ACTION_CALL
        //Android.Net.Uri uri = Android.Net.Uri.Parse(callForwardString);
        //callIntent.SetData(uri);
        //Android.App.Application.Context.StartActivity(callIntent);


        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        AlertDialog alert = dialog.Create();
        alert.SetTitle("Title");
        alert.SetMessage("Simple Alert");
        alert.SetButton("OK", (s, ev) =>
        {
            alert.SetMessage("This is an alert message");
        });

        alert.Show();
    }

    public void StopCallDiverting()
    {
        //Stop the call diverting action
    }
}

我应该如何解决这个问题才能成功测试 dependencyService?

最佳答案

如果您只有一个 Activity 应用程序,您可能只需传入即可

Android.App.Application.Context

例如

AlertDialog.Builder dialog = new AlertDialog.Builder(Android.App.Application.Context);

然而,要在多 Activity 应用程序中获取当前 Activity 上下文,则需要跟踪它

有关如何跟踪当前上下文的信息,请参阅此答案

https://stackoverflow.com/a/47363378/1612975

关于c# - Xamarin C# 无法将 c# 类转换为 Android.content.context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51057616/

相关文章:

c# - 使用 HtmlAgilityPack 的 doctype 问题

c# - ActionFilterAttribute 的 Ninject 2 属性注入(inject)不起作用

android截取屏幕外页面

java - Eclipse 和 Android SDK 停止工作

android - 'mono shared runtime' 始终部署到 android 设备

c# - 使用 Linq 进行数学统计

c# - 任务中的阻塞方法

android - Etsy 的 StaggeredGridview 是否可以在 API 9 中工作?

android - 大位图的平铺和缩放技术

针对填充列表的 C# foreach 返回 null