【问题标题】:Xamarin Android passing MainActivity to AlertDialogXamarin Android 将 MainActivity 传递给 AlertDialog
【发布时间】:2015-08-31 15:31:04
【问题描述】:

我正在尝试通过将 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 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);

【问题讨论】:

  • 您需要使用该活动的上下文来显示警报对话框
  • 当我尝试使用 AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());它说“名称 getApplicationContext 在当前上下文中不存在。

标签: android xamarin android-alertdialog


【解决方案1】:
public class AlertViewController: Activity

AlertViewController 扩展了 Activity...因此您的 AlertViewController 充当 Activity,因此它应该在清单中注册,并且还应该使用 Intent 启动...稍后使用主题将其转换为对话框...或

一个解决方案只是创建一个简单的类

public class AlertViewController

并在构造函数中传递活动上下文

AlertViewController alertView = new AlertViewController (YourActivity.this);
alertView.ShowAlertBox ("Test", "Test");

另一种解决方案扩展 Dialog 类并创建自定义对话框

public class AlertViewController : Dialog

否则您也可以使用对话框片段...更多信息请查看http://javatechig.com/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android

【讨论】:

    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多