gpt4 book ai didi

android - 在 Xamarin.Forms 中访问 Android 上下文

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:28:36 24 4
gpt4 key购买 nike

我见过一些使用 Xamarin.Forms 获取 Android 上下文的旧解决方案。这些较旧的解决方案建议使用 Xamarin.Forms.Forms.Context但由于不断变化的 Xamarin.Forms 平台,这不再适用。

在我的示例中,我使用了 DependencyService.Get<Interface>()从我的共享代码项目中使用 Interface 的平台特定实现类。

在使用 Xamarin.Andriod 使用平台特定功能时,需要大量使用 Android Context。

那么我们如何获取Android Context的全局信息接口(interface)呢?

最佳答案

  1. 转到您在解决方案的 App.Droid 项目部分创建的类。
  2. 确保您在顶部包含using Android.Content;
  3. 创建一个变量来保存 Context 并使用 Android.App.Application.Context 对其进行初始化。

就是这样!

using Android.Content;

[assembly: Xamarin.Forms.Dependency(typeof(DroidClass))]
namespace App.Droid
{
public class DroidClass : Interface
{
Context context = Android.App.Application.Context;

public DroidClass()
{
Toast.MakeText(context, "Grabbed Context!", ToastLength.Long).Show();
}
}
}

关于android - 在 Xamarin.Forms 中访问 Android 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44937590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com