简体   繁体   English

将int传递给其他活动会导致奇怪的行为

[英]Passing ints into other activity causes strange behavior

I am passing 3 ints from MainActivity to main and displaying them in separate Textviews . 我将3个intsMainActivity传递给main并将它们显示在单独的Textviews When I click button to go to next activity, it shows the last passed int in the last textview. 当我单击按钮转到下一个活动时,它将在最后一个textview中显示最后一个传递的int Pressing the back button on my smartphone, it resets the last textview to 0 and shows the correct value for the second textview. 按下智能手机上的“后退”按钮,它将上一个文本视图重置为0,并显示第二个文本视图的正确值。 Then pressing the back button again, it resets the second textview to 0 and shows the correct value for the first textview. 然后再次按返回按钮,它将第二个文本视图重置为0并显示第一个文本视图的正确值。

Code inside OnCreate method at MainActivity.java : MainActivity.java OnCreate方法内的代码:

            Intent sendX = new Intent(MainActivity.this, main.class);
            sendX.putExtra("x", x);
            startActivity(sendX);
            Intent sendY = new Intent(MainActivity.this, main.class);
            sendY.putExtra("y", y);
            startActivity(sendY);
            Intent sendZ = new Intent(MainActivity.this, main.class);
            sendZ.putExtra("z", z);
            startActivity(sendZ);

Code inside OnCreate method at main.class : main.class OnCreate方法内的代码:

    Intent getX = getIntent();
    x = getX.getIntExtra("x", 0);
    Intent getY = getIntent();
    y = getY.getIntExtra("y", 0);
    Intent getZ = getIntent();
    z = getZ.getIntExtra("z", 0);

    TextView test1 = (TextView)findViewById(R.id.testx);
    test1.setText(Integer.toString(x));
    TextView test2 = (TextView)findViewById(R.id.testy);
    test2.setText(Integer.toString(y));
    TextView test3 = (TextView)findViewById(R.id.testz);
    test3.setText(Integer.toString(z));

You need to read up on how Intents work some more. 您需要进一步了解Intent的工作原理。 You're basically starting 3 instances of the same Activity. 您基本上是在启动同一Activity的3个实例。 Do this instead: 改为这样做:

Intent intent = new Intent(MainActivity.this, main.class);
intent.putExtra("x", x);
intent.putExtra("y", y);
intent.putExtra("z", z);
startActivity(intent);

and

Intent intent = getIntent();
x = intent.getIntExtra("x", 0);
y = intent.getIntExtra("y", 0);
x = intent.getIntExtra("z", 0);

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

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