1

スピナーを含むカスタム ダイアログを表示したい。しかし、そうすると、setAdapter() メソッドで NullPointerException が発生します。1 週間以上試してみましたが、これを正しく行う方法がわかりませんでした。ここに私のコードがあります:

     AlertDialog alertDialog;

     LayoutInflater inflater = 
                 (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);                          
     View layout = inflater.inflate(R.layout.form,
                                    (ViewGroup) findViewById(R.id.layout_root));

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

    //I get the error in the following line:

    try{ 

         spinner.setAdapter(spinnerAdapter);

    }catch(Exception exception){
         Toast.makeText(getApplicationContext(),
    "Exception: "+exception,Toast.LENGTH_SHORT).show();
      }

     AlertDialog.Builder  builder = new AlertDialog.Builder(this);
     builder.setView(layout);
     alertDialog = builder.create();
     alertDialog.setTitle("Security");
     alertDialog.show();
   }

xml ファイル form.xml は次のとおりです。

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


  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   android:id="@+id/layout_root" >


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

  </LinearLayout> 

私を助けてください。リンクをたどりました:ダイアログ内のスピナー - 同じ問題について説明している NullPointerException ですが、それでもできませんでした。

4

2 に答える 2

2

Spinner spinner = (Spinner) findViewById(R.id.spinner1); ここではできません。使用する必要がありますlayout.findviewById(...)..(layout_root にスピナーがあることを願っています)。

于 2012-01-06T07:20:57.533 に答える
2

これを試して:

Spinner spinner = (Spinner)layout.findViewById(R.id.spinner1);

于 2012-01-06T07:21:05.063 に答える