android ZXing条码扫描器内的对话框片段

beq87vna  于 2023-09-28  发布在  Android
关注(0)|答案(1)|浏览(107)

我想创建一个包含条形码扫描仪预览的DialogFragment,它将处理扫描结果并将其返回给Activity。
这是我现在的代码。一切工作正常,但当扫描器解码任何代码时,应用程序关闭(没有抛出错误)。

public class ScanFragment extends DialogFragment implements DialogInterface.OnKeyListener {
    private final Context context;

    private FragmentScanBinding binding;

    private CaptureManager capture;
    private IResultCallback callback;

    public ScanFragment(Context context, IResultCallback callback) {
        this.context = context;
        this.callback = callback;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentScanBinding.inflate(getLayoutInflater());

        binding.btnCancel.setOnClickListener(view -> dismiss());

        BarcodeView view = binding.getRoot().findViewById(R.id.zxing_barcode_surface);
        view.setFramingRectSize(new Size(600, 300));

        capture = new CaptureManager(requireActivity(), binding.zxingBarcodeScanner);
        capture.initializeFromIntent(requireActivity().getIntent(), savedInstanceState);
        capture.setShowMissingCameraPermissionDialog(false);
        capture.decode();

        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        capture.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        capture.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        capture.onDestroy();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        capture.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
        return (binding.zxingBarcodeScanner).onKeyDown(keyEvent.getKeyCode(), keyEvent);
    }
}

我也想将我的IResultCallback绑定到CaptureManager的结果,但我只是不知道如何将其绑定到相机。

t3irkdon

t3irkdon1#

因此,对我来说最好的解决方案是实现自己的CaptureManager,并使其不适用于Activity,而是适用于传递到构造函数的回调函数。我还必须实现另一个初始化函数,因为我不使用intent。

相关问题