Spinner in dialog - NullPointerException

二次信任 提交于 2019-12-07 11:40:45

问题


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


来源:https://stackoverflow.com/questions/6365268/spinner-in-dialog-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!