Set spinner within custom dialog

前端 未结 1 519
余生分开走
余生分开走 2021-01-25 08:27

I\'m getting a NullPointerException while attempting to create a Spinner within a dialog and can\'t seem to debug it because the code looks solid. Wonder if anyone else has any

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-25 08:41

    I have managed to fix the issue. It was very subtle and I'm pretty sure I got lucky. Here's the working code:

    protected Dialog onCreateDialog(int id)
        {
            Dialog dialog;
            switch(id) {
            case DIALOG_SEND_PM:
                dialog = new Dialog(PM.this);
                dialog.setContentView(R.layout.send_pm_dialog);
                dialog.setTitle(R.string.send_pm);
                pmMessage = (EditText) dialog.findViewById(R.id.send_pm_box);
                Button sendPm = (Button) dialog.findViewById(R.id.send_pm_button);
                sendPm.setOnClickListener(PM.this);
    
                Spinner spinner = (Spinner)dialog.findViewById(R.id.pm_server);
                ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.server_array, android.R.layout.simple_spinner_item);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinner.setAdapter(adapter);
                spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
                break;
            default:
                dialog = null;
            }
            return dialog;
        }
    

    I moved some of the code around so that the dialog was initialized before the spinner, but that was not the issue. I added dialog. in Spinner spinner = (Spinner)dialog.findViewById(R.id.pm_server); and that did the trick. Hope this helps others.

    0 讨论(0)
提交回复
热议问题