I am trying to create a custom dialog box with two spinners ( spinner_month
and spinner_year
).
For guidance, I took the sample provided in Google dev guide.
MainActivity code:
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);
My calender_view.xml is as follows
<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>
When I run it I get the following error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter) on a null object reference
This is because the 'spinner' object is null
, but I'm not sure why. Is there something I am missing?
Try this one
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater li = LayoutInflater.from(this);
View view = li.inflate(R.layout.calender_view, null, false);
builder.setView(view);
AlertDialog alertDialog = builder.create();
Spinner spinner = (Spinner) view.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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.