我这辈子都弄不明白为什么会出现 NullPointerException。
当用户点击特定图像时,应该会弹出一个对话窗口并显示该图像的放大版本:
private OnClickListener coverListener = new OnClickListener()
{
public void onClick(View v)
{
showDialog(DIALOG_COVER);
}
};
DIALOG_COVER 设置为 = 0。
关联的 onCreateDialog 如下所示:
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id)
{
case DIALOG_COVER:
dialog = new Dialog(mContext);
dialog.setContentView(R.layout.cover_dialog);
dialog.setTitle(book.getTitle());
ImageView coverLarge = (ImageView)findViewById(R.id.coverLarge);
coverLarge.setImageBitmap(book.getCover());
break;
default:
dialog = null;
}
return dialog;
}
作为引用,这是 cover_dialog.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/coverDialog"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="@+id/coverLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitStart"
/></LinearLayout>
现在,当单击前面描述的图像时,应用程序立即崩溃并通过 LogCat 抛出以下错误:
06-08 13:29:17.727: ERROR/AndroidRuntime(2220): Uncaught handler: thread main exiting due to uncaught exception
06-08 13:29:17.757: ERROR/AndroidRuntime(2220): java.lang.NullPointerException
06-08 13:29:17.757: ERROR/AndroidRuntime(2220): at org.kylehughes.android.brarian.AndroidBrarian.onCreateDialog(AndroidBrarian.java:259)
有问题的行是指 onCreateDialog 中的这一行:
coverLarge.setImageBitmap(book.getCover());
基本上,我当时不明白为什么 coverLarge 为 null。任何帮助将不胜感激。
最佳答案
关于什么:
/** snip **/
LayoutInflater factory = LayoutInflater.from(mContext);
View dialogView = factory.inflate(R.layout.cover_dialog,null);
ImageView coverLarge = (ImageView)dialogView.findViewById(R.id.coverLarge);
dialog = new Dialog(mContext);
dialog.setContentView(dialogView);
dialog.setTitle(book.getTitle());
coverLarge.setImageBitmap(book.getCover());
/** snip **/
刚刚从头开始编写。请检查语法
关于java - Android 自定义对话框 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999855/