【问题标题】:Can't show a simple message in an Android App无法在 Android 应用中显示简单消息
【发布时间】:2015-10-22 00:34:57
【问题描述】:

我今天开始使用 Visual Studio 2015 开发 Android 应用程序,我想知道为什么我不能显示 AlertDialog,因为它会抛出一个关于 Android.Views.WindowManagerBadTokenException 的异常,我看不出我在哪里弄错了..

private void Button_Click(object sender, EventArgs e)
{
    ((Button)sender).Text = string.Format("{0} clicks!", count++);
    try
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.ApplicationContext);
        builder.SetTitle("This is a title..");
        builder.SetMessage("This is a message..");
        AlertDialog ad = builder.Create();
        ad.Show();
    }
    catch (Exception ex)
    { ((Button)sender).Text = ex.Message; }
}

【问题讨论】:

  • this.ApplicationContext 为什么?为什么不直接使用this?
  • 我想我必须发送ApplicationContext,因为它在构造函数中请求上下文..
  • 由于某种原因,alertdialog 请求一个上下文,但只适用于活动上下文(漂亮的设计,android ......)。你需要在这里活动。 (this 可能是一个活动,不是吗?)

标签: android visual-studio-2015


【解决方案1】:

首先,如果您刚开始为 Android 开发,请使用 ANDROID STUDIOS,除非您有充分的理由在 Visual Studios 中进行开发。 Android Studios 是我用过的最好的 IDE,我强烈推荐它。

但是,如果您想坚持使用 Visual Studios,请尝试以下代码:

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
alertDialog.show();

从this 问题中提取。也许是因为你的 .Create() 和 .Show() 应该都是小写而不是驼峰式。

【讨论】:

  • new AlertDialog.Builder(this) 正如 njzk2 所说,为我工作。
  • 哦,好吧,太棒了。但说真的,在Android Studios 中,它会立即发现该错误。我强烈推荐它。
猜你喜欢
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多