我正在尝试构建BMI计算器应用程序,但是,使用意图和方法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");
}
}
我真的陷在这个问题上。非常感谢大家!
在第一次活动中
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);`
用于其他活动
Bundle bundle = getIntent().getExtras();
int weight = Integer.parseInt(bundle.getString("USER_WEIGHT_EXTRA"));
int height = Integer.parseInt(bundle.getString("USER_HEIGHT_EXTRA"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句