无法访问片段的 onActivityResult zxing

Can't access onActivityResult zxing for fragment

我正在尝试通过片段中的 Zxing 读取条码

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_caddie, container, false);
    etCodigo = v.findViewById(R.id.etCodigo);
    btnLeerCodigo = v.findViewById(R.id.btnLeerCodigo);

    btnLeerCodigo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            escanear();
        }
    });
    text = "";

    return v;
}


public void escanear() {

    IntentIntegrator intent = IntentIntegrator.forSupportFragment(FragmentCaddie.this);
    //IntentIntegrator intent = new IntentIntegrator(getActivity());
    intent.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
    intent.setPrompt("ESCANEAR CODIGO");
    intent.setCameraId(0);
    intent.setBeepEnabled(false);
    intent.setBarcodeImageEnabled(false);
    intent.initiateScan();

}


 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

    if(result != null) {
        if(result.getContents() == null) {
            Toast.makeText(getContext(), "Cancelaste el escaneo", Toast.LENGTH_SHORT).show();
        } else {
            text = text + " + " +  result.getContents().toString() ;
            etCodigo.setText(text);
            escanear();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

问题是它无法访问 onActivityResult

托管 activity 覆盖 onActivityResult(),但它没有为未处理的结果代码调用 super.onActivityResult()。显然,即使片段是进行 startActivityForResult() 调用的片段,activity 也会率先处理结果。当您考虑片段的模块化时,这是有道理的。一旦我为所有未处理的结果实现了 super.onActivityResult(),该片段就开始处理结果。

看看这个:

onActivityResult is not being called in Fragment

希望对你有用:)

解决方案非常简单,我实施的 onActivityResult 被父 activity

覆盖

解决方案是从父 activity

调用片段 onActivityResult
private static final int BARECODE_REQUEST = 114910;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {     

    if (requestCode == BARECODE_REQUEST) {
        super.onActivityResult(requestCode,resultCode,data);
    }
}