我到处搜索,找不到关于如何在Fragment中实现ZXing的有效解决方案。多个消息源告诉我,这是正确的,但从未调用onActivityResult。
单击按钮会触发扫描仪打开
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.fragment_barcode,container,false);
final Button openBC = (Button)view.findViewById(R.id.btnOpen);
openBC.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//This opens up the Barcode Scanner
IntentIntegrator integrator = new IntentIntegrator(getActivity());
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan A barcode or QR Code");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
return view;
}
这是应该处理扫描结果的位置,但是永远不会到达这里
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(getActivity(), "canceled",Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(getActivity(),"Scanned: " + result.getContents(),Toast.LENGTH_LONG).show();
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
最佳答案
发生这种情况是因为您从Fragment覆盖了onActivityResult,但使用活动初始化了intentIntegrator IntentIntegrator integrator = new IntentIntegrator(getActivity());
。
您有两种选择:
1)覆盖Activity内部的onActivityResult
2)更改活动实例内部的初始化传递片段。
这应该可以帮助您:
假设该片段称为MyFragment:
IntentIntegrator.forFragment(MyFragment.this).initiateScan();
ZXing Minimal