我有一个警报对话框,其中包含用户可能要作为构建器项目访问的网站名称的数组。现在的名字是Facebook,我希望当通过DialogClick事件处理程序单击该项目时在类中声明的WebView加载Facebook网址,但是我在类中声明的所有变量(包括Webview)对该DialogClick事件处理程序不可见,想我应该尝试一个函数指针或委托,但卡住了请帮助... 警报对话框的C#代码以及侦听下面点击的项目的方法
class Internet : AppCompatActivity,Android.Webkit.IDownloadListener, GestureDetector.IOnGestureListener, BottomNavigationView.IOnNavigationItemSelectedListener, IDialogInterfaceOnClickListener
{
WebView webview;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.Browser);
//webview definition
webview=this.FindViewById<WebView>(Resource.Id.webview1);
//Button that shows the dialog on click
Button f=this.FindViewById<Button>(Resource.Id.button1);
f.Click +=show;
}
//Method to build and show alert dialog
private void show(object sender, EventArgs e){
string[] items = new string[5] { "Facebook", "Google", "Instagram", "Twitter","Reddit" };
Android.Support.V7.App.AlertDialog.Builder builder =new Android.Support.V7.App.AlertDialog.Builder(this);
builder.SetTitle("Menu Items");
builder.SetIcon(Resource.Drawable.avatar);
//This function pointer in here called handler is the one that handles the dialog click event
builder.SetItems(items, handler);
});
dialog.Show();
}
//Handler method to take care of an item clicked on the dialog
EventHandler<DialogClickEventArgs> handler = (s, o) => {
// save off selected event
switch (o.Which)
{
case 0:
Toast.MakeText(Application.Context, "You tapped on facebook", ToastLength.Short).Show();
//Tried to make variable webview load facebook url but the variable is invisible to this scope
break;
case 1:
Toast.MakeText(Application.Context, "You tapped on Google", ToastLength.Short).Show();
break;
case 4:
Toast.MakeText(Application.Context, "You tapped on Reddit", ToastLength.Short).Show();
break;
}
};
}
我需要使该类中声明的所有webview变量在此方法中可见的代码,或者使该Webview可见的另一种方法的有效函数指针可以为我加载网址
答案 0 :(得分:1)
您可以用另一种方式定义处理程序:
class Internet : AppCompatActivity
{
public WebView webview;
EventHandler<DialogClickEventArgs> handler { get; set; }
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
handler += test;
}
public void test(object sender, DialogClickEventArgs e)
{
switch (e.Which)
{
case 0:
Toast.MakeText(Application.Context, "You tapped on facebook", ToastLength.Short).Show();
//Tried to make variable webview load facebook url but the variable is invisible to this scope
webview.LoadUrl("123");
break;
case 1:
Toast.MakeText(Application.Context, "You tapped on Google", ToastLength.Short).Show();
break;
case 4:
Toast.MakeText(Application.Context, "You tapped on Reddit", ToastLength.Short).Show();
break;
}
}
}