2

我试图将 SurfaceView 与相机一起使用。但是,findViewById(R.id.mySurfaceView) 返回 null。有趣的是,我在 MainActivity 中使用了完全相同的代码,效果很好。只有当我把它放到另一个活动中时它才会出错(我复制了所有的 xmls 和东西)。

我的主要活动只有这个:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(this, CammmActivity.class);
    startActivity(intent);
}
}

这是CameraActivity

public class CammmActivity extends Activity implements SurfaceHolder.Callback{

Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

      getWindow().setFormat(PixelFormat.UNKNOWN);
      surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
      surfaceHolder = surfaceView.getHolder();
      surfaceHolder.addCallback(this);
      surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
 int height) {
// TODO Auto-generated method stub
if(previewing){
 camera.stopPreview();
 previewing = false;
}

if (camera != null){
 try {
  camera.setPreviewDisplay(surfaceHolder);
  camera.startPreview();
  previewing = true;
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}

xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".CammmActivity" >

<SurfaceView 
android:id="@+id/camerapreview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

</RelativeLayout>
4

1 回答 1

0

我测试了您的代码,它在我的设备上运行良好。尝试刷新和清理您的项目 Project -> Clean。

于 2013-06-04T20:08:52.467 回答