对话框中的微调器 - NullPointerException

时间:2011-06-15 22:37:36

标签: android dialog spinner

我想用微调器显示自定义对话框。奇怪的是,当我尝试设置微调器的适配器时,我得到NullPointerException ...

Dialog dialog = new Dialog(this.getApplicationContext());
dialog.setContentView(R.layout.dialog_spinner);

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

spin = (Spinner)dialog.findViewById(R.id.spinQ);
//What am I doing wrong here?
spin.setAdapter(spinnerAdapter);

dialog.setTitle("Questions");
dialog.show();

xml布局代码:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:paddingLeft="10dip"
>

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


</LinearLayout>

更新

        AlertDialog alertDialog;


        LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.dialog_spinner,
                                       (ViewGroup) findViewById(R.id.root));

        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
              android.R.layout.simple_spinner_item, new String[] {"0","1","2"});
        spin = (Spinner) findViewById(R.id.spinQ);
        //I get the error in the following line:
        spin.setAdapter(spinnerAdapter);

        builder = new AlertDialog.Builder(mContext);
        builder.setView(layout);
        alertDialog = builder.create();
        alertDialog.show();

1 个答案:

答案 0 :(得分:10)

你的Spinner可能还没有膨胀。如果您想操纵视图,请自行充气,然后在充气setContentView上使用View。请参阅创建对话框上的docs

<强>更新

在新代码中,更改:

spin = (Spinner) findViewById(R.id.spinQ);

为:

spin = (Spinner) layout.findViewById(R.id.spinQ);