android - 对话框中的微调器 - NullPointerException - Android

标签 android spinner android-alertdialog android-spinner customdialog

我想显示一个带有微调器的自定义对话框。但是当我这样做时,我在 setAdapter() 方法中得到 NullPointerException。我已经尝试了一个多星期,但无法弄清楚如何正确解决这个问题。这是我的代码:

     AlertDialog alertDialog;

     LayoutInflater inflater = 
                 (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);                          
     View layout = inflater.inflate(R.layout.form,
                                    (ViewGroup) findViewById(R.id.layout_root));

     ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
           android.R.layout.simple_spinner_item, new String[] {"0","1","2"});
     Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    //I get the error in the following line:

    try{ 

         spinner.setAdapter(spinnerAdapter);

    }catch(Exception exception){
         Toast.makeText(getApplicationContext(),
    "Exception: "+exception,Toast.LENGTH_SHORT).show();
      }

     AlertDialog.Builder  builder = new AlertDialog.Builder(this);
     builder.setView(layout);
     alertDialog = builder.create();
     alertDialog.setTitle("Security");
     alertDialog.show();
   }

这是 xml 文件 form.xml:

  ?xml version="1.0" encoding="utf-8"?>


  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   android:id="@+id/layout_root" >


   <Spinner
    android:id="@+id/spinner1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

  </LinearLayout> 

请帮帮我。我点击了链接:Spinner in dialog - NullPointerException 其中讨论了同样的问题,但我还是做不到。

最佳答案

试试这个:

微调器 spinner = (Spinner)layout.findViewById(R.id.spinner1);

关于android - 对话框中的微调器 - NullPointerException - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8754603/

相关文章:

android - 单击 Android Spinner 仅在模拟器上抛出 NullPointerException

android - 如何为 Android 中的 Spinner 设置错误消息?

java - 暂停直到函数完成运行

java - Android studio 中的入职屏幕

android - 那么下一步按钮在新的 Activity 窗口中不起作用

java - 我在 SqLite 中得到了错误的日期

java - android 未知的空指针错误

android - 我们在哪里可以下载 Android 支持库的以前版本?

android - 如何更改微调器的标题

android - 当我单击“返回”按钮时,“警报”对话框和“进度”对话框关闭