Bal
保持重置为0。
Continue = (Button)findViewById(R.id.btnContinue);
Continue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent startIntent = new Intent(SecondActivity.this, Mainmenu.class);
int Bal = Integer.parseInt(Balance.getText().toString());
int MonthlyTarget = Integer.parseInt(Target.getText().toString());
startIntent.putExtra("intBalance", Bal);
startIntent.putExtra("intTarget", MonthlyTarget);
startActivity(startIntent);
}
});
另一项活动:
Intent startIntent = getIntent();
int Bal = startIntent.getIntExtra("intBalance", 0);
int MonthlyTarget = startIntent.getIntExtra("intTarget", 0);
Intent RecordExpense = getIntent();
int Expense = RecordExpense.getIntExtra("intExpense", 0);
Intent RecordIncome = getIntent();
int Income = RecordIncome.getIntExtra("intIncome", 0);
TextView tvResult=(TextView) findViewById(R.id.tvResult);
tvResult.setText(Bal +"");
if(getIntent().hasExtra("intIncome")) {
Bal=Bal+Income;
tvResult.setText(Bal + "");
}
if(getIntent().hasExtra("intExpense")) {
Bal=Bal-Expense;
tvResult.setText(Bal + "");
}
每当我将
5
作为余额,并且将3
作为费用时,我都希望输出为2
。但是实际输出是-3
最佳答案
您要在Intent
中将“ intBalance”放入0,而不是将值Bal
放入。
Continue = (Button)findViewById(R.id.btnContinue);
Continue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent startIntent = new Intent(SecondActivity.this, Mainmenu.class);
int Bal = Integer.parseInt(Balance.getText().toString());
int MonthlyTarget = Integer.parseInt(Target.getText().toString());
// Change 0 to Bal
startIntent.putExtra("intBalance", Bal);
startIntent.putExtra("intTarget", MonthlyTarget);
startActivity(startIntent);
}
});
PS-
尝试遵循命名约定,尽管看起来似乎无关紧要,但是当变量名看起来像类名时,很容易错过简单的事情。
另外,不要不必要地创建诸如
startIntent
,RecordExpense
和RecordExpense
之类的变量。 getIntent()
已经使您可以访问该意图,您不需要每次都获取并将其引用存储在变量中。关于java - 传递的整数值始终会重置为默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57075701/