0
我试图用两个微调器(spinner_month
和spinner_year
)创建一个自定义对话框。创建自定义对话框时出错
有关指导,我参考了Google开发指南中提供的示例。
MainActivity代码:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.calender_view);
AlertDialog alertDialog = builder.create();
Spinner spinner = (Spinner) alertDialog.findViewById(R.id.spinner_month);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.months_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
我calender_view.xml如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal"
android:padding="5dp">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner_year"
android:layout_weight="1"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner_month"
android:layout_weight="1"
android:spinnerMode="dialog"/>
</LinearLayout>
当我运行它,我得到以下错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter) on a null object reference
这是因为'微调对象是null
,但我不知道为什么。有什么我失踪?
这个答案是所有代码。请考虑添加一些说明,解释为什么这个答案可以解决问题。 – RedBassett
根据建议 - 我添加了LayoutInflater,然后夸大了'calender_view'并将其分配给适配器 它完美地工作! – Vivek
当我第一次调用'builder.show'时,它工作正常。但随后的调用失败与'java.lang.IllegalStateException:指定的孩子已经有一个父' 所以我的假设是正确的,我需要创建对话框,每次我需要它,而不是我可以在'onCreate() '只需简单地调用'builder.show()',我觉得效率会更高效 – Vivek