android 计算BMI
时间: 2023-12-16 21:03:29 浏览: 33
以下是一个计算BMI的 Android 代码示例:
首先,创建一个布局文件 `activity_main.xml`,包含两个输入框和一个按钮:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editTextWeight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Weight (kg)"/>
<EditText
android:id="@+id/editTextHeight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Height (m)"/>
<Button
android:id="@+id/buttonCalculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate"/>
<TextView
android:id="@+id/textViewResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
```
然后,在 `MainActivity.java` 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private EditText editTextWeight;
private EditText editTextHeight;
private Button buttonCalculate;
private TextView textViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextWeight = findViewById(R.id.editTextWeight);
editTextHeight = findViewById(R.id.editTextHeight);
buttonCalculate = findViewById(R.id.buttonCalculate);
textViewResult = findViewById(R.id.textViewResult);
buttonCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String weightString = editTextWeight.getText().toString();
String heightString = editTextHeight.getText().toString();
if (weightString.isEmpty() || heightString.isEmpty()) {
textViewResult.setText("Please enter weight and height.");
return;
}
float weight = Float.parseFloat(weightString);
float height = Float.parseFloat(heightString);
float bmi = weight / (height * height);
String result = String.format("Your BMI is %.2f", bmi);
textViewResult.setText(result);
}
});
}
}
```
这个代码首先在 `onCreate` 方法中找到了布局文件中的所有视图,并在按钮点击事件中计算了BMI值,最后在 `TextView` 中显示了结果。
运行应用程序并输入体重和身高,点击计算按钮,就会显示计算出来的BMI值。