1.打开Android Studio并创建一个新的项目。
2. 选择"Empty Activity"模板并点击"Next"。
3. 为项目命名,例如"BMIQueryApp",然后选择项目位置和保存位置。点击"Finish"以创建项目。
4. 在项目的`res/layout`目录下,找到`activity_main.xml`文件并打开它。这是应用程序的主界面布局文件。
5. 在`activity_main.xml`文件中,添加两个EditText用于输入身高和体重,一个Button用于执行查询操作,以及一个TextView用于显示查询结果。示例代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<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="wrap_content"
android:layout_height="wrap_content"
android:text="计算BMI" />
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BMI结果" />
</LinearLayout>
6. 在项目的`src/main/java`目录下,找到`MainActivity.java`文件并打开它。这是应用程序的主活动文件。
7. 在`MainActivity.java`文件中,为计算按钮添加点击事件监听器,并在点击事件中执行BMI计算操作。示例代码如下:
package com.example.bmiqueryapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText etHeight;
private EditText 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) {
double height = Double.parseDouble(etHeight.getText().toString()) / 100; // 将身高转换为米
double weight = Double.parseDouble(etWeight.getText().toString());
double bmi = weight / (height * height);
tvResult.setText("您的BMI值为:" + String.format("%.2f", bmi));
}
});
}
}
8. 运行应用程序并进行测试。