Spinner in dialog - NullPointerException

2019-05-07 01:37发布

问题:

I want to show custom dialog with a spinner. Strangely enough, I get NullPointerException when I try to set the adapter of the spinner...

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();

The xml layout code:

<?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>

UPDATE:

        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:

Your Spinner is probably not inflated yet. If you want to manipulate the views, inflate it yourself and then use setContentView on the inflated View. See the docs on Creating Dialogs.

Update:

In your new code, change:

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

to:

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