大家好日子如何将Android MainActivity中的字符串值或数据传递给PCL TabbedPage?
MainActivity.cs
using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using Android.Telephony;
using Xamarin.Forms;
namespace NegDrClient.Droid
{
[Activity (Label = "Neg Client", Icon = "@drawable/logo", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
global::ZXing.Net.Mobile.Forms.Android.Platform.Init ();
LoadApplication (new App ());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult (requestCode, permissions, grantResults);
}
public string GetNumber()
{
TelephonyManager telephonyManager =
(TelephonyManager) Forms.Context.GetSystemService(Android.Content.Context.TelecomService);
var number = telephonyManager.Line1Number;
return number.ToString();
}
}
}
我需要调用GetNumber()方法,以便将其分配给我的登录条目,谢谢。
答案 0 :(得分:4)
您可以通过依赖服务执行此操作。
将以下界面添加到您的Xamarin.Forms项目中:
public interface IPhone
{
string GetNumber();
}
将该界面添加到MainActivity
项目中的现有Xamarin.Android
:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity, IPhone
注册该依赖类(在namespace NegDrClient.Droid
之上):
[assembly: Xamarin.Forms.Dependency(typeof(MainActivity))]
现在您可以在Xamarin.Forms
项目中调用它:
var GetNumberButton = new Button()
{
Command = new Command(() => {
Device.BeginInvokeOnMainThread(() =>
{
var number = DependencyService.Get<IPhone>().GetNumber();
System.Diagnostics.Debug.WriteLine(number);
});
})
};
注意:您的GetNumber
方法中有错误,应该是:
public string GetNumber()
{
var telephonyManager = (TelephonyManager)Forms.Context.GetSystemService(Context.TelephonyService);
return telephonyManager.Line1Number;
}