Xamarin Android将MainActivity传递给AlertDialog
我试图通过在另一个类中分离其代码并根据代码中的要求调用该类来实现AlertDialog 下面是我的AlertDialogXamarin Android将MainActivity传递给AlertDialog,android,xamarin,android-alertdialog,Android,Xamarin,Android Alertdialog,我试图通过在另一个类中分离其代码并根据代码中的要求调用该类来实现AlertDialog 下面是我的AlertDialog using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace NAndroid { public class AlertViewControlle
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace NAndroid
{
public class AlertViewController: Activity
{
public AlertViewController ()
{
}
public void ShowAlertBox (string titleTxt, string messageTxt)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetTitle(titleTxt);
builder.SetMessage(messageTxt);
builder.SetCancelable(false);
builder.SetPositiveButton("OK", delegate { Finish(); });
RunOnUiThread (() => {
builder.Show();
} );
}
}
}
从别的班上叫它
AlertViewController alertView = new AlertViewController ();
alertView.ShowAlertBox ("Test", "Test");
它正在冲线。它抛出空指针异常
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertViewController扩展活动…因此您的AlertViewController充当活动,因此应在清单中注册它,并应使用意图启动它…稍后使用主题将其转换为对话框…或
一种解决方案是创建一个简单的类
public class AlertViewController
并在构造函数中传递活动上下文
AlertViewController alertView = new AlertViewController (YourActivity.this);
alertView.ShowAlertBox ("Test", "Test");
另一个解决方案是扩展对话框类并创建自定义对话框
public class AlertViewController : Dialog
或者,您也可以查看对话框片段…有关更多信息,请检查当我尝试使用AlertDialog.Builder=new AlertDialog.Builder(getApplicationContext())时,您需要使用该活动的上下文,在该上下文上显示AlertDialog;它表示“getApplicationContext名称在当前上下文中不存在。
public class AlertViewController : Dialog