Android Studio Java中Activity传值计算每日卡路里需求求助
实现步骤说明
整个流程分为主Activity传参、第二个Activity接收参数计算两个核心环节,具体实现代码如下:
1. 主Activity(MainActivity)实现
- 首先在
activity_main.xml中添加跳转按钮,示例布局代码:
<Button android:id="@+id/btn_calculate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="计算每日卡路里" />
- 然后在
MainActivity.java中绑定按钮点击事件,获取参数并跳转:
public class MainActivity extends AppCompatActivity { // 示例变量,可根据实际需求替换成自己的输入来源(比如EditText输入值) private double weight = 65.5; // 体重 单位kg private double height = 175.2; // 身高 单位cm private double age = 28.0; // 年龄 private double gender = 1; // 1代表男性,0代表女性,可根据自己的规则调整 private double activityCoefficient = 1.2; // 活动系数,久坐1.2,轻度运动1.375等 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnCalculate = findViewById(R.id.btn_calculate); btnCalculate.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, SecondActivity.class); // 传入double参数,键名自定义保持两端一致即可 intent.putExtra("weight", weight); intent.putExtra("height", height); intent.putExtra("age", age); intent.putExtra("gender", gender); intent.putExtra("activity_coefficient", activityCoefficient); startActivity(intent); }); } }
2. 第二个Activity(SecondActivity)实现
- 先在
activity_second.xml中添加显示结果的TextView:
<TextView android:id="@+id/tv_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" />
- 然后在
SecondActivity.java中接收参数,调用计算逻辑:
public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); TextView tvResult = findViewById(R.id.tv_result); // 接收传递的double参数,默认值可根据需求自定义 double weight = getIntent().getDoubleExtra("weight", 0); double height = getIntent().getDoubleExtra("height", 0); double age = getIntent().getDoubleExtra("age", 0); double gender = getIntent().getDoubleExtra("gender", 1); double activityCoefficient = getIntent().getDoubleExtra("activity_coefficient", 1.2); // 调用方法计算每日所需卡路里,这里用通用的Mifflin-St Jeor公式 double calory = calculateDailyCalory(weight, height, age, gender, activityCoefficient); tvResult.setText("每日所需卡路里:" + String.format("%.1f", calory) + " 千卡"); } /** * 计算每日所需卡路里 * @param weight 体重 kg * @param height 身高 cm * @param age 年龄 * @param gender 1=男性 0=女性 * @param coefficient 活动系数 * @return 每日所需卡路里 */ private double calculateDailyCalory(double weight, double height, double age, double gender, double coefficient) { double bmr; if (gender == 1) { bmr = 10 * weight + 6.25 * height - 5 * age + 5; } else { bmr = 10 * weight + 6.25 * height - 5 * age - 161; } return bmr * coefficient; } }
注意事项
- 确保你已经在
AndroidManifest.xml中注册了SecondActivity - 如果参数是来自用户输入的EditText,记得要做非空判断和格式校验,避免转double时报崩溃
- 你可以根据自己的需求调整计算公式、参数数量,只要保证Intent传递时的键名和接收时完全一致即可
内容的提问来源于stack exchange,提问作者Ksunit
相关产品推荐
相关产品推荐

