我正在尝试构建一个BMI计算器应用程序,但是,使用intent和方法getIntExtra()似乎有问题,因为我总是得到默认值而不是我从另一个活动传入的值。 以下是我的第一个活动的代码
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
int weight = Integer.parseInt(weightText.getText().toString());
int height = Integer.parseInt(heightText.getText().toString());
intent.putExtra(USER_WEIGHT_EXTRA, weight);
intent.putExtra(USER_HEIGHT_EXTRA, height);
startActivity(intent);
}
});
第二项活动
双height2 = (double)height/100
的原因是从cm转换为m。
result = (TextView)findViewById(R.id.result);
todo = (TextView) findViewById(R.id.todo);
Intent intent = getIntent();
int weight = intent.getIntExtra("USER_WEIGHT_EXTRA", extraInt);
int height = intent.getIntExtra("USER_HEIGHT_EXTRA", extraInt);
double height2 = (double)height/100;
double BMI = (weight*1.0)/(height2*height2);
if (BMI < 20.0) {
result.setText("You are: UNDERWEIGHT");
todo.setText("You Should EAT MORE");
} else if (BMI > 20.0 && BMI < 25.0) {
result.setText("You are: NORMAL WEIGHT");
todo.setText("You Should keep STAYING HEALTHY");
} else if (BMI > 25) {
result.setText("You are: OVERWEIGHT");
todo.setText("You Should EXERCISE MORE");
}
}
我真的被困在这个问题上了。非常感谢你们!
答案 0 :(得分:0)
在第一项活动中
Intent in = new Intent(this, OtherActivity.class);
in.putExtra("USER_WEIGHT_EXTRA", weightText.getText().toString());
in.putExtra("USER_HEIGHT_EXTRA", heightText.getText().toString());
startActivity(in);`
for otherActivity
Bundle bundle = getIntent().getExtras();
int weight = Integer.parseInt(bundle.getString("USER_WEIGHT_EXTRA"));
int height = Integer.parseInt(bundle.getString("USER_HEIGHT_EXTRA"));