对话框中的Spinner - NullPointerException [英] Spinner in dialog - NullPointerException

查看:173
本文介绍了对话框中的Spinner - NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

您的 Spinner 可能还没有膨胀。如果要操作视图,请自己充气,然后在膨胀的视图上使用 setContentView 。请参阅创建对话框上的文档

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.

更新:

在新代码中,更改:

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

to:

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

这篇关于对话框中的Spinner - NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆