我想显示一个带有微调器的自定义对话框。但是当我这样做时,我在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 in dialog - NullPointerException 讨论同样的问题,但我仍然无法做到。
答案 0 :(得分:2)
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
你不能在这里做到这一点。你需要使用layout.findviewById(...)..
(我希望你的layout_root有微调器)。
答案 1 :(得分:2)
试试这个:
Spinner spinner = (Spinner)layout.findViewById(R.id.spinner1);