为什么在调用OnBackPressed时我的应用程序崩溃了?

时间:2018-09-13 17:07:55

标签: c# xamarin xamarin.forms

我正试图在按下后退按钮(OnBackPressed)时执行一些javascript(webview Eval),但应用程序崩溃了。有人可以弄清楚发生了什么吗?

MainActivity.cs

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        /*
     some code
    */
        base.OnCreate(savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }

    public override void OnBackPressed()
    {
        MainPage.ExecJS();
}
}

MainPage.xaml.cs

 public partial class MainPage : ContentPage
 {
    public static double ScreenWidth { get; set; }
    public static double ScreenHeight { get; set; }
    public static WebView webnav;
    StackLayout parent = null;
    public MainPage()
    {
        InitializeComponent();
        WebView webnav = new WebView
        {
            HeightRequest = 1000,
            WidthRequest = 1000,
            Source = "https://www.comprarmusicas.com.br/mobile/index.php"
        };
        parent = new StackLayout();
        parent.Children.Add(webnav);
        Content = parent;
    }

     public static void ExecJS()
    {
        string jsCode = "alert('ok');";
        webnav.Eval(jsCode);
    }
 }

1 个答案:

答案 0 :(得分:0)

您不是在.ctor中分配静态WebView变量,而是创建一个新的本地实例变量。

从您实例化/分配WebView的位置删除WebView类型,即

public MainPage()
{
    InitializeComponent();
    webnav = new WebView // this assigns to the "public static WebView webnav;"
    {
        HeightRequest = 1000,
    ~~~