我正在尝试创建一个扩展 SurfaceView
的自定义视图 GhostSurfaceCameraView
. 这是我的类定义文件
GhostSurfaceCameraView.java
:
public class GhostSurfaceCameraView extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Camera mCamera;
GhostSurfaceCameraView(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where to draw.
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
// TODO: add more exception handling logic here
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(w, h);
parameters.set("orientation", "portrait");
// parameters.setRotation(90); // API 5+
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
这是在我的ghostviewscreen.xml中:
<com.alpenglow.androcap.GhostSurfaceCameraView android:id="@+id/ghostview_cameraview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
现在我做的活动:
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.ghostviewscreen);
}
}
调用 setContentView()
时,抛出异常:
Binary XML file 09-17 22:47:01.958: ERROR/ERROR(337):
ERROR IN CODE:
android.view.InflateException: Binary
XML file line #14: Error inflating
class
com.alpenglow.androcap.GhostSurfaceCameraView
谁能告诉我为什么会出现这个错误?谢谢 .
9 回答
就我而言,我从其他地方复制了我的课程,并没有立即注意到它是一个
abstract
课程 . 你不能夸大抽象类 .在过去的几个小时里,我有这个错误困扰着我 . 事实证明,我已将自定义视图库添加为Android Studio中的模块,但我忽略了将其添加为应用程序
build.gradle
中的依赖项 .在我的情况下我添加了这样的循环资源:
然后改为
它工作
我在扩展TextEdit时遇到了同样的问题 . 对我来说,错误是我没有添加"public"到构造函数 . 在我的情况下,即使我只定义了一个构造函数,即带有参数
Context
和AttributeSet
的构造函数,它仍然有效 . 有线的事情是,只有当我构建一个APK(有罪或无法)并将其传输到设备时,该bug才会显示出来 . 当应用程序通过AndroidStudio - > RunApp在USB连接设备上运行时,应用程序可以运行 .我想我弄清楚为什么这不起作用 . 当我应该为两个参数'Context,AttributeSet'的情况提供构造函数时,我只提供了一个参数'context'的构造函数 . 我还需要为构造函数提供公共访问权限 . 这是我的修复:
“错误膨胀类”消息的另一个可能原因可能是错误拼写在XML中指定的完整包名称:
在Eclipse XML编辑器中打开布局XML文件应突出显示此问题 .
fwiw,我收到此错误是由于构造函数中的某些自定义初始化尝试访问null对象 .
在xml中编写完整的类路径很重要 . 当只写入子类的名字时,我得到了'错误膨胀类' .
@Tim - 两个构造函数都不是必需的,只需要
ViewClassName(Context context, AttributeSet attrs )
构造函数 . 经过几个小时的浪费时间后,我发现了这种痛苦的方式 .我对Android开发很新,但我在这里做了一个疯狂的猜测,可能是因为我们在XML文件中添加了自定义
View
类,我们在XML中设置了几个属性,需要在实例化时处理 . 比我知识渊博的人能够更清楚地了解这件事 .