在 AlertDialog 中有一個 inflated layout 。當我提及到它其中的一個 view 時,獲取一個 NullpointerException。
dialog_with_spinner.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp">
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="@string/info_title" />
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:entries="@array/entries"
android:saveEnabled="true"/>
</LinearLayout>
<CheckBox
android:id="@+id/someId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/someString"/>
</LinearLayout>
Code:
AlertDialog.Builder builder = new AlertDialog.Builder(boxThemeContextWrapper);
LayoutInflater inflater = getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_with_spinner, null))
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
final Spinner sp = (Spinner) findViewById(R.id.spinner);
int p = sp.getSelectedItemPosition(); // this gets the **NullPointerException**
String[] entryValues = getResources().getStringArray(R.array.entry_values);
final String entry = entryValues[p];
useMyEntryMethod(entry);
}
})
.setNegativeButton(R.string.dialogs_negative, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//
}
});
builder.show();
如何處理這個問題呢?
(Spinner) findViewById(R.id.spinner);這裡其實返回的是空的,你應該用
inflater.inflate(R.layout.dialog_with_spinner, null)這個返回的view,再view.findViewById,