题
我试图制定摄像头预览自定义窗口小部件。我想,以填补与相机预览屏幕,并得出一些按钮在它。
我试图创建一个定制窗口小部件的方式如下:
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
class CapturePreview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Camera mCamera;
CapturePreview(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 = 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);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
和修改的文件main.xml中按以下方式:
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout">
<dev.video.client.CapturePreview android:id="@+id/capturePreview" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</RelativeLayout>
在Activity类我试图微件通过以下方式结合:
private CapturePreview mPreview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setFullscreen();
setContentView(R.layout.main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//mPreview = new CapturePreview(this);
//setContentView(mPreview);
mPreview = (CapturePreview)this.findViewById(R.id.capturePreview);
}
每次我尝试调试应用程序,我得到一个错误信息,我还没有发现什么可能是错误的。
我真的很感激,关于这个问题的任何帮助。
谢谢!
解决方案
您需要为此创造SurfaceView下面的构造工作:
CapturePreview(Context context, AttributeSet attrs)
正如你可能知道,在Java中构造函数是不能继承的,从它的父类,但是这是Android的尝试,当你使用一个XML文件组件(而不是编程方式定义你的GUI)来调用构造函数。这是行不通的,当然,因此错误信息,这应该是有更多更清晰,在我看来。
在的AttributeSet 包含提到的每个属性在XML声明中,所以如果你有你的组件自定义属性,您可以检索并采取相应行动,在构造函数中。
其他提示
可以实现onTouchListener()到尊重视图。当你永远点击表面上自动Android系统将带你到onTouchListener()方法。
不隶属于 StackOverflow