我正试图在按下后退按钮(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);
}
}
答案 0 :(得分:0)
您不是在.ctor中分配静态WebView
变量,而是创建一个新的本地实例变量。
从您实例化/分配WebView的位置删除WebView
类型,即
public MainPage()
{
InitializeComponent();
webnav = new WebView // this assigns to the "public static WebView webnav;"
{
HeightRequest = 1000,
~~~