Android 将相机预览从 Activity 发送到 Fragment TextureView

Android send Camera Preview from Activity to Fragment TextureView

我的 Fragment 中有一个 TextureView 并且 Fragment 必须重新填充布局。我在Activity中使用CameraAPI(PS:相机API必须在Activity中调用),我可以使用SurfaceTexture 获取相机预览。

请问如何让TextureView可以获取Camera预览。我厌倦了很多解决方案,但所有解决方案都得到了空对象引用。

public class MyFragment extends PresentationFragment{
    private TextureView textureView;
    private TextView textView;
    public View onCreateView(LayoutInflater layoutInflater, @Nullable ViewGroup contatiner, Bundle savedInstanceState) {
        rootView = layoutInflater.inflate(R.layout.external_display, contatiner, false);
        textureView = rootView.findViewById(R.id.camera_view);
        textView = rootView.findViewById(R.id.test_text);

        return rootView;
    }

}

在Activity中:

private MyFragment myFragment;
private TextureView textureView;
private SurfaceTexture surfaceTexture;

在 onCreate 中:

myFragment =(myFragment)getFragmentManager().findFragmentById(R.id.external_display);
View view = myFragment.getView();
textureView = view.findViewById(R.id.camera_preview);
surfaceTexture = textureView.getSurfaceTexture();

getView() 空对象引用。

这就是您的 Activity 生命周期。片段视图在 onCreate 中不可用。幸运的是,这应该不是问题:在 onRestore 之前初始化相机是不正确的。