[英]Xamarin Android passing MainActivity to AlertDialog
I am trying to implement the AlertDialog by separating its code in another class and calling that class as required in the code. 我试图通过将警报代码分离到另一个类中并根据代码中的要求调用该类来实现AlertDialog。
Here is how i have my AlertDialog 这是我的AlertDialog的方式
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();
} );
}
}
}
To call it from other class 从其他班级调用
AlertViewController alertView = new AlertViewController ();
alertView.ShowAlertBox ("Test", "Test");
It is crashing at the line. 它崩溃了。 It throws Null Pointer Exception 它抛出空指针异常
AlertDialog.Builder builder = new AlertDialog.Builder(this);
public class AlertViewController: Activity
AlertViewController extends Activity...hence your AlertViewController acts as a activity so it should be registered in the manifest and it should also be started using intent...later using theme to convert it into dialog...OR AlertViewController扩展了Activity ...因此您的AlertViewController充当了一个活动,因此应将其注册在清单中,还应使用intent来启动...稍后使用主题将其转换为对话框...或
One Solution just create a simple class as 一个解决方案只是创建一个简单的类
public class AlertViewController
And in Constructor pass the activity context 并在构造函数中传递活动上下文
AlertViewController alertView = new AlertViewController (YourActivity.this);
alertView.ShowAlertBox ("Test", "Test");
Another Solution extend Dialog class and create custom dialog 另一个解决方案扩展了Dialog类并创建自定义对话框
public class AlertViewController : Dialog
or else you can go for dialog fragments as well...for more info check http://javatechig.com/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android 否则,您也可以获取对话框片段...有关更多信息,请参见http://javatechig.com/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.