如何在片段类中使用其他活动功能

时间:2019-06-01 07:50:01

标签: java android

请帮助我,我是android开发的新手。我想在我的家庭片段中使用其他活动类功能(在这种情况下为QR码扫描仪),我该如何使用它?

public class HomeFragment extends Fragment {

    public Button scan_btn;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        scan_btn = (Button) view.findViewById(R.id.scan_btn);
        scan_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(getActivity(), QR_Reader.class);
                startActivity(in);
            }
        });
        return view;
    }

}

活动代码

public class QR_Reader extends AppCompatActivity  {

        private Button scan_btn;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.fragment_home);
            scan_btn = (Button) findViewById(R.id.scan_btn);
            final Activity activity = this;
            scan_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    IntentIntegrator integrator = new IntentIntegrator(activity);
                    integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
                    integrator.setPrompt("Scan QR Code");
                    integrator.setCameraId(0);
                    integrator.setBeepEnabled(false);
                    integrator.setBarcodeImageEnabled(false);
                    integrator.initiateScan();
                }
            });

            Bundle bundle = getIntent().getExtras();
        }

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

    }

我想在我的家庭片段中使用QR扫描仪。我试图运行该程序,但是每当我单击“扫描”按钮时,该程序都会关闭。 请帮助我。

0 个答案:

没有答案