我想创建一个简单的计算器,无论我在文本视图中编写什么内容,我都将第二活动的值设为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));
答案 0 :(得分:2)
如评论中所述。您还需要将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);
答案 1 :(得分: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);
intent.putExtras(extras);
startActivity(intent);
您忘记了putExtras()方法!