Android Camera preview in a fragment

前端 未结 2 1480
盖世英雄少女心
盖世英雄少女心 2020-12-17 00:47

Until now I have a full working code that plugs in a camera to see the preview of the front camera.

What I\'m trying to do now is to get that camera working inside

相关标签:
2条回答
  • 2020-12-17 01:12

    At first - use FrameLayout for your camera preview.

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mainLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    

    The second - no need to open camera two times. Your surfaceCreated method.

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(holder);
                mCamera.setPreviewCallback(new Camera.PreviewCallback() {
                    @Override
                    public void onPreviewFrame(byte[] data, Camera camera) {
                    }
                });
            }
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
        }
    }
    

    The third - no need to release camera two times. You did it in Fragment, just remove it from surfaceDestroyed.

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (mCamera != null)
            {
    //          mCamera.stopPreview();
    //          mCamera.release();
            }
        }
    

    And in your fragment.

    @Override
    public void onPause() {
        super.onPause();
    
        if (mCamera != null)
        {
            mCamera.stopPreview();
            mCamera.release();
        }
    }
    

    And you will see your camera preview in a fragmentas I see. Good luck!

    0 讨论(0)
  • 2020-12-17 01:13

    It seems you have attribute cameraId in CameraExtractionFragment and CameraExtraction, but this is assigned a value only in CameraExtractionFragment.

    You should remove CameraExtraction.cameraId and use CameraExtractionFragment.cameraId instead.

    0 讨论(0)
提交回复
热议问题