繁体   English   中英

如何使用Intent启动活动并在新活动中传递变量?

[英]How to I launch an activity with an Intent and pass a variable in the new activity?

所以现在我在我的应用程序中使用zxing条形码扫描仪。 这是示例代码(通用):

if(position == 0){
            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
            intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
            startActivityForResult(intent, 0);


        }

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                contents = intent.getStringExtra("SCAN_RESULT");
                format = intent.getStringExtra("SCAN_RESULT_FORMAT");
                // Handle successful scan
                Intent i = new Intent(Main.this, BarcodeScanner.class);
                startActivity(i);
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }

因此,在启动BarcodeScanner.class ,我还想将contents传递给它。 我该怎么做呢?

在意图内使用Bundle将数据从一个活动传递到另一个活动。 在你的情况下,你必须做类似的事情 -

        Intent intent = new Intent(Main.this,BarcodeScanner.class);

        //load the intent with a key "content" and assign it's value to content            
        intent.putExtra("content",contents);

        //launch the BarcodeScanner activity and send the intent along with it
        //note that content  is passed in as well             
        startActivity(intent);

信息存储在Intent内部的“Bundle”对象中 - 当您调用Intent对象的putExtras()方法时会创建Bundle

"SCAN_MODE"传递给另一个活动的方法与调用startActivity()之前调用putExtra("some key", contents) startActivity() ,然后在BarcodeScanner中调用this.getIntent this.getIntent().getStringExtra("some key")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM