簡體   English   中英

Dialog中的微調器 - NullPointerException - Android

[英]Spinner in Dialog - NullPointerException - Android

我想顯示一個帶有微調器的自定義對話框。 但是當我這樣做時,我在setAdapter()方法中得到了NullPointerException。我已經嘗試了一個多星期了,並且無法弄清楚如何做到這一點。 這是我的代碼:

     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> 

請幫幫我。 我跟着鏈接: Spinner在對話框中 - NullPointerException討論了同樣的問題,但我仍然無法做到。

Spinner spinner = (Spinner) findViewById(R.id.spinner1); 你不能在這里做到這一點。 你需要使用layout.findviewById(...).. (我希望你的layout_root有微調器)。

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM