繁体   English   中英

无法传递字符串值

[英]Can't pass string value

我想创建一个简单的计算器,无论我在文本视图中写什么,我都会得到 0 的第二个活动的值。

    Intent intent = new Intent(this, DisplayResultActivit.class );
    EditText edittext = findViewById(R.id.liczba);
    EditText edittext2 = findViewById(R.id.liczba2);
    int wpis2 = Integer.valueOf(edittext.getText().toString());
    int wpis = Integer.valueOf(edittext2.getText().toString());
    Bundle extras = new Bundle();
    extras.putInt("wpis", wpis);
    extras.putInt("wpis2", wpis2);
    startActivity(intent);

2 活动:

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    int wpis = 0;
    if (extras != null) {
        wpis = extras.getInt("wpis1");
    }
    int wpis2 = 0;
    if (extras != null) {
        wpis2 = extras.getInt("wpis2");
    }


    TextView tv = findViewById(R.id.result);
        tv.setText(String.valueOf(wpis) + String.valueOf(wpis2));

正如评论中提到的。 您还需要将 Bundle 变量与 Intent 变量链接起来。 请参阅以下链接: https : //zocada.com/using-intents-extras-pass-data-activities-android-beginners-guide/

//create a Bundle object
Bundle extras = new Bundle();
//Adding key value pairs to this bundle
//there are quite a lot data types you can store in a bundle
extras.putString("USER_NAME","jhon Doe");
extras.putInt("USER_ID", 21);
extras.putIntArray("USER_SELCTIONS", [1, 2, 3, 4, 5]);
...
//create and initialize an intent
Intent intent = new Intent(this, NextActivity.class);
//attach the bundle to the Intent object
intent.putExtras(extras);
//finally start the activity
startActivity(intent);

所以你的代码需要是:

Intent intent = new Intent(this, DisplayResultActivit.class );
EditText edittext = findViewById(R.id.liczba);
EditText edittext2 = findViewById(R.id.liczba2);
int wpis2 = Integer.valueOf(edittext.getText().toString());
int wpis = Integer.valueOf(edittext2.getText().toString());
Bundle extras = new Bundle();
extras.putInt("wpis", wpis);
extras.putInt("wpis2", wpis2);

intent.putExtras(extras);

startActivity(intent);

只需将您的代码更改为:

Intent intent = new Intent(this, DisplayResultActivit.class );
EditText edittext = findViewById(R.id.liczba);
EditText edittext2 = findViewById(R.id.liczba2);
int wpis2 = Integer.valueOf(edittext.getText().toString());
int wpis = Integer.valueOf(edittext2.getText().toString());
Bundle extras = new Bundle();
extras.putInt("wpis", wpis);
extras.putInt("wpis2", wpis2);
intent.putExtras(extras);
startActivity(intent);

你忘记了 putExtras() 方法!

暂无
暂无

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

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