Untitled
unknown
plain_text
8 months ago
8.0 kB
8
Indexable
package com.example.bmicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText weightEditText;
private EditText heightEditText;
private RadioButton maleRadioButton;
private RadioButton femaleRadioButton;
private Button calculateButton;
private TextView resultTextView;
private Button resetButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // Replace 'main' with your layout file name if different
weightEditText = (EditText) findViewById(R.id.weightEditText);
heightEditText = (EditText) findViewById(R.id.heightEditText);
maleRadioButton = (RadioButton) findViewById(R.id.maleRadioButton);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleRadioButton);
calculateButton = (Button) findViewById(R.id.calculateButton);
resultTextView = (TextView) findViewById(R.id.resultTextView);
resetButton = (Button) findViewById(R.id.resetButton);
calculateButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
calculateBMI();
}
});
resetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
resetFields();
}
});
}
private void calculateBMI() {
String weightStr = weightEditText.getText().toString();
String heightStr = heightEditText.getText().toString();
if (weightStr.equals("") || heightStr.equals("")) {
Toast.makeText(this, "Please enter both weight and height.", Toast.LENGTH_SHORT).show();
return;
}
float weight = Float.parseFloat(weightStr);
float heightCm = Float.parseFloat(heightStr);
float heightM = heightCm / 100; // Convert cm to meters
if (heightM <= 0) {
Toast.makeText(this, "Please enter a valid height.", Toast.LENGTH_SHORT).show();
return;
}
float bmi = weight / (heightM * heightM);
resultTextView.setText(String.format("%.2f", bmi));
}
private void resetFields() {
weightEditText.setText("");
heightEditText.setText("");
maleRadioButton.setChecked(true);
femaleRadioButton.setChecked(false);
resultTextView.setText("");
}
}
}
}
}
}
}
})
}
})
}
}Editor is loading...
Leave a Comment