zxing onActivityResult仅在Activity中没有调用Fragment

时间:2013-11-16 00:48:55

标签: android android-intent zxing onactivityresult

我在使用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, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    System.out.println("the code is catch");
}

}

10 个答案:

答案 0 :(得分:33)

由于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);
    }
}

答案 1 :(得分:8)

integrator.initiateScan();

将上述行更改为

integrator.forSupportFragment(fragment_name.this).initiateScan();

答案 2 :(得分:3)

如果有任何人有同样的问题,这是我的解决方案。

package com.example.testingcodereading;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);

FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentById(R.id.fragmentContainer);

if (f == null) {
  f = MainFragment.newInstance("Start Application");
  fm.beginTransaction().add(R.id.fragmentContainer, f).commit();
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
  Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
System.out.println("the code is catch");

IntentResult scanResult = IntentIntegrator.parseActivityResult(
    requestCode, resultCode, intent);
// handle scan result
if (scanResult != null) {
  FragmentManager fm = getSupportFragmentManager();

  Fragment newFrame = MainFragment.newInstance(scanResult.toString());

  fm.beginTransaction().replace(R.id.fragmentContainer, newFrame).commit();
}

}

}

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.test.suitebuilder.annotation.MediumTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainFragment extends Fragment {

private static final String EXTRA_CODE = "com.example.testingcodereading.code";
private Button mButtonXZing;
private TextView mTextView;


public static MainFragment newInstance(String code) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CODE, code);

MainFragment fragment = new MainFragment();
fragment.setArguments(args);

return fragment;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle    savedInstanceState){
View v = inflater.inflate(R.layout.fragment_main, parent, false);

mTextView = (TextView) v.findViewById(R.id.text_code);
mTextView.setText((String) getArguments().getSerializable(EXTRA_CODE));

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) {
super.onActivityResult(requestCode, resultCode, 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
}

}

答案 3 :(得分:2)

替代 ZXing Android Embedded ,实施:

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    new IntentIntegrator(this).initiateScan(); // `this` is the current Activity

}

从片段中使用:

IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment

// If you're using the support library, use: 
// IntentIntegrator.forSupportFragment(this) instead.

获得结果:

@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(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
        Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
    }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

more info and options

答案 4 :(得分:1)

确保OnActivityResult中的Activity正在呼叫super.OnActivityResult()。这应该确保它也被Fragment调用。

或者,您可以修改IntentIntegrator代码,使其在StartActivityResult上调用Fragment,方法是将片段传递给构造函数,或将其传递给initiateScan

答案 5 :(得分:1)

我遇到了这个问题,并使用以下代码解决了该问题:

IntentIntegrator integrator = new IntentIntegrator(getActivity());                
integrator.forSupportFragment(MyFragment.this).initiateScan();

答案 6 :(得分:0)

解决方案:如何管理它的基本示例

主要活动

public static int tapTrick = 0;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    if(tapTrick!=0 && tapTrick==1) {
        Tab1.onActivityResult(requestCode, resultCode, data, MainActivity.this);
    }else if (tapTrick!=0 && tapTrick==2){
        //Tab2.onActivityResult(requestCode, resultCode, data, MainActivity.this);
    }
}

片段1

MainActivity.tapTrick=1; // onCreateView  or onClick (load images/files)

 public static void onActivityResult(int requestCode, int resultCode, Intent intent, Context context) {
 }

片段2

MainActivity.tapTrick=2;
 public static void onActivityResult(int requestCode, int resultCode, Intent intent, Context context) {
 }

片段x

MainActivity.tapTrick=x;
 public static void onActivityResult(int requestCode, int resultCode, Intent intent, Context context) {
 }

答案 7 :(得分:0)

尝试如下在IntentIntegrator中创建Fragment对象。

        val scanIntegrator = IntentIntegrator.forSupportFragment(this@HomeFragment)
        scanIntegrator.setPrompt("Scan")
        scanIntegrator.setBeepEnabled(true)
        //The following line if you want QR code
        scanIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES)
        scanIntegrator.captureActivity = CaptureActivityAnyOrientation::class.java
        scanIntegrator.setOrientationLocked(true)
        scanIntegrator.setBarcodeImageEnabled(true)
        scanIntegrator.initiateScan()

答案 8 :(得分:0)

应以这种方式调用扫描:

IntentIntegrator.forSupportFragment(YourFragment.this)
                    .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
                    .setBeepEnabled(true/false)
                    .setPrompt("blahblahblah")
                    .initiateScan();

然后您可以在Fragment的onActivityResult中获取扫描结果

答案 9 :(得分:0)

public void scanCode() {
        IntentIntegrator.forSupportFragment(this).
        setCaptureActivity(CaptureAct.class).
        setOrientationLocked(false)
        .setDesiredBarcodeFormats(IntentIntegrator.PRODUCT_CODE_TYPES)
        .setPrompt("Scanning code")
        .initiateScan();
    }