android studiobmi计算
时间: 2023-11-21 13:58:05 浏览: 44
以下是Android Studio中实现BMI计算的步骤:
1. 在布局文件中添加两个EditText用于输入身高和体重,一个Button用于触发计算BMI的操作,一个TextView用于显示计算结果。
```xml
<EditText
android:id="@+id/et_height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入身高(米)"/>
<EditText
android:id="@+id/et_weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入体重(千克)"/>
<Button
android:id="@+id/btn_calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="计算BMI"/>
<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"/>
```
2. 在Activity中获取布局文件中的控件,并为Button设置点击事件。
```java
public class MainActivity extends AppCompatActivity {
private EditText etHeight, etWeight;
private Button btnCalculate;
private TextView tvResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etHeight = findViewById(R.id.et_height);
etWeight = findViewById(R.id.et_weight);
btnCalculate = findViewById(R.id.btn_calculate);
tvResult = findViewById(R.id.tv_result);
btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在这里编写计算BMI的代码
}
});
}
}
```
3. 在Button的点击事件中编写计算BMI的代码,并将结果显示在TextView中。
```java
btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 获取输入的身高和体重
double height = Double.parseDouble(etHeight.getText().toString());
double weight = Double.parseDouble(etWeight.getText().toString());
// 计算BMI
double bmi = weight / (height * height);
// 显示计算结果
tvResult.setText("您的BMI指数为:" + bmi);
}
});
```