androidbmi体质指数计算器代码和详细步骤
时间: 2024-01-21 08:04:29 浏览: 53
以下是一个简单的 Android BMI(Body Mass Index,身体质量指数)计算器的代码和详细步骤。
1. 创建一个新的 Android 项目,并在 `activity_main.xml` 文件中添加以下代码来创建用户界面:
```xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/edit_weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Weight (kg)" />
<EditText
android:id="@+id/edit_height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Height (m)" />
<Button
android:id="@+id/button_calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate BMI" />
</LinearLayout>
```
这会创建一个包含两个输入框和一个按钮的线性布局。
2. 在 `MainActivity.java` 文件中添加以下代码来处理按钮点击事件和计算BMI:
```java
public class MainActivity extends AppCompatActivity {
private EditText mEditWeight;
private EditText mEditHeight;
private Button mButtonCalculate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditWeight = findViewById(R.id.edit_weight);
mEditHeight = findViewById(R.id.edit_height);
mButtonCalculate = findViewById(R.id.button_calculate);
mButtonCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String weightString = mEditWeight.getText().toString();
String heightString = mEditHeight.getText().toString();
if (!TextUtils.isEmpty(weightString) && !TextUtils.isEmpty(heightString)) {
float weight = Float.parseFloat(weightString);
float height = Float.parseFloat(heightString);
float bmi = weight / (height * height);
Toast.makeText(MainActivity.this, "Your BMI is " + bmi, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Please enter your weight and height.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
```
这段代码首先获取体重和身高的输入值,然后将它们转换为浮点数,并计算BMI。最后,使用 `Toast` 显示计算结果。
3. 运行应用程序并输入体重和身高。单击“Calculate BMI”按钮,应该会显示计算出来的BMI值。
请注意,这只是一个简单的示例,实际的BMI计算可能需要更复杂的算法和逻辑。此外,还应该添加错误处理和输入验证,以防止用户输入无效的值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)