我希望能够将相机从后切换到前(或从前切换到后)
使用此代码,当我启动应用程序时,第一个开关可以工作,但其他开关则不能:

  public void changeCameraOnFly(View v)
  {
       if (isPreview) {camera.stopPreview();}
       camera.release();

           System.out.println("Camera ID before : " + String.valueOf(cameraID));
       if(cameraID == 0) {cameraID++;}
       if(cameraID == 1) {cameraID--;}
       System.out.println("Camera ID after: " + String.valueOf(cameraID));

           camera = Camera.open(cameraID);
           try {
                //this step is critical or preview on new camera will no know where to render to
                camera.setPreviewDisplay(surfaceCamera.getHolder());
           }
           catch (IOException e) { e.printStackTrace(); }
       camera.startPreview();
  }


调试日志:

06-17 18:27:43.594: I/System.out(10551): Camera ID before : 1
06-17 18:27:43.594: I/System.out(10551): Camera ID after: 0
06-17 18:27:46.074: I/System.out(10551): Camera ID before : 0
06-17 18:27:46.074: I/System.out(10551): Camera ID after: 0

最佳答案

cameraId为0时,您的第一个if语句为true。因此cameraId递增到1。

然后,您的应用程序继续到下一行,在该行中检查cameraId是否为1。的确如此,因此cameraId递减为0。

尝试使用if-else代替。例如:

if (cameraId == 0) {
    cameraId++;
} else if (cameraId == 1) {
    cameraId--;
} else {
    // Default: Do nothing
}

10-08 07:12