我在zxing onActivityResult()中遇到一些问题.
正如您可以在代码中看到的,我已经正确地调用了https://code.google.com/p/zxing/wiki/ScanningViaIntent所述的新意图.
问题是如何在Fragment中捕获onActivityResult(),因为我需要Fragmnet中的这些数据而不是Activity?
package com.example.testingcodereading; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class MainFragment extends Fragment { private Button mButtonXZing; @Override public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle savedInstanceState){ View v = inflater.inflate(R.layout.fragment_main,parent,false); mButtonXZing = (Button) v.findViewById(R.id.button_xzing); mButtonXZing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(getActivity()); integrator.initiateScan(); } }); return v; } @Override public void onActivityResult(int requestCode,int resultCode,Intent intent) { System.out.println("never here"); IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,intent); if (scanResult != null) { // handle scan result } // else continue with any other code you need in the method } }
public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fm = getSupportFragmentManager(); Fragment f = fm.findFragmentById(R.id.fragmentContainer); if(f == null){ f = new MainFragment(); fm.beginTransaction() .add(R.id.fragmentContainer,f) .commit(); } } @Override protected void onActivityResult(int requestCode,Intent intent) { super.onActivityResult(requestCode,intent); System.out.println("the code is catch"); } }
解决方法
正如Martynnw指出的那样,问题是调用fragment.startActivityForResult而不是activity.startActivityForResult.所以只需使用下一个包装:
import android.content.Intent; import android.support.v4.app.Fragment; import com.google.zxing.integration.android.IntentIntegrator; public final class FragmentIntentIntegrator extends IntentIntegrator { private final Fragment fragment; public FragmentIntentIntegrator(Fragment fragment) { super(fragment.getActivity()); this.fragment = fragment; } @Override protected void startActivityForResult(Intent intent,int code) { fragment.startActivityForResult(intent,code); } }