2012-01-06 95 views
1

我想显示一个自定义对话框,其中包含一个微调器。但是,当我做我得到NullPointerException在setAdapter()方法。我一直在尝试了一个多星期,现在无法弄清楚如何得到这个权利。这里是我的代码:Spinner in Dialog - NullPointerException - Android

 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 它讨论了同样的问题,但我仍然无法做到这一点。

+0

您需要添加微调查看动态/编程您的活动类的代码,并设置这方面的活动。 – jeet 2012-01-06 07:17:51

回答

2

试试这个:

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

+0

这只是解决了问题!非常感谢你:) – 2012-01-06 11:13:38

+0

@vickey:对你的一个小建议,谷歌首先在你发布任何问题之前。它会为你节省很多时间。 – 2012-01-06 12:50:18

+0

获取错误:类型为R.layout的findViewById(int)方法未定义 – Neo 2014-08-15 06:00:42

2

Spinner spinner = (Spinner) findViewById(R.id.spinner1);你不能在这里这样做。你需要使用layout.findviewById(...)..(我希望你的layout_root有微调)。

+1

3年后保存我的日子= D,谢谢!!! – user2582318 2015-06-28 14:09:34

+1

@ user2582318:很高兴帮助!祝你好运! – kosa 2015-06-29 04:07:58