@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextureView = (TextureView) findViewById(R.id.textureView1);
mTextureView.setSurfaceTextureListener(this);
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width,
int height) {
mCamera = Camera.open(0);
try {
mCamera.setPreviewTexture(surface);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mCamera.stopPreview();
mCamera.release();
return false;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// TODO Auto-generated method stub
}
目前,当我运行此程序时,相机会自动启动。如何在按钮点击时启动相机。我尝试使用点击按钮。但是屏幕上没有可用的纹理视图。请建议
答案 0 :(得分:0)
你的布局文件中应该有一个按钮和一个TextureView,如
您的相机正在自动呼叫,因为只要您的TextureView准备好就会调用onSurfaceTextureAvailable
。因此,您可以在onSurfaceTextureAvailable
内准备好TextureView之后设置一个按钮监听器,而不是调用Camera目录。
以下是相同的代码段。
在 main_layout.xml
内 <TextureView
android:id="@+id/ttv"
android:text="@string/hello_world"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />
现在内部onCreate()
或OnCreateView()
{如果是片段}
使用Button
TextureView
和findViewById(...)
public class MainActivity extends ActionBarActivity implements TextureView.SurfaceTextureListener{
TextureView tv;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tv = (TextureView) rootView.findViewById(R.id.ttv);
tv.setSurfaceTextureListener(this);
b = (Button) rootView.findViewById(R.id.button);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
final SurfaceTexture surfaceT = surface;
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera = Camera.open(0);
try {
mCamera.setPreviewTexture(surfaceT);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
});
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mCamera.stopPreview();
mCamera.release();
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
不要忘记在清单文件中添加这些摄像机权限和功能:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />