在MainActivity.java中,给EditText设置焦点获取和输入监听,RadioGroup设置单选监听,以及Calculate按钮设置点击监听
时间: 2024-10-24 13:09:50 浏览: 35
在`MainActivity.java`中,你需要为EditText、RadioGroup和Calculate按钮分别设置焦点获取、输入监听、单选监听和点击监听。以下是一个简化的例子:
```java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class MainActivity extends AppCompatActivity {
private EditText editTextNum1, editTextNum2;
private RadioGroup radioGroupOperators;
private Button buttonCalculate;
private int selectedOperator = -1; // 初始化未选中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取UI控件
editTextNum1 = findViewById(R.id.editText_num1);
editTextNum2 = findViewById(R.id.editText_num2);
radioGroupOperators = findViewById(R.id.radioGroup_operators);
buttonCalculate = findViewById(R.id.button_calculate);
// 设置EditText焦点获取和输入监听
editTextNum1.requestFocus(); // 立即聚焦到第一个EditText
editTextNum1.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
// 当文本改变时,更新其他控件状态等
}
});
// 设置RadioGroup单选监听
radioGroupOperators.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != -1) { // 防止首次点击时的空值
selectedOperator = checkedId;
switch (selectedOperator) {
case R.id.radioButton_plus:
// 执行加法操作...
break;
// 其他运算符的case
}
}
}
});
// 设置Calculate按钮点击监听
buttonCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String num1 = editTextNum1.getText().toString();
String num2 = editTextNum2.getText().toString();
if (!num1.isEmpty() && !num2.isEmpty()) {
// 根据selectedOperator执行计算
double result = performCalculation(num1, num2, selectedOperator);
updateResult(result);
} else {
Toast.makeText(MainActivity.this, "请输入完整数值", Toast.LENGTH_SHORT).show();
}
}
private double performCalculation(String num1, String num2, int operatorId) {
// 实现具体的计算逻辑...
}
private void updateResult(double result) {
TextView textViewResult = findViewById(R.id.textView_result);
textViewResult.setText("结果: " + result);
}
});
}
}
```
在这个代码片段中,我们为EditText设置了文本改变后的回调,RadioGroup设置了单选切换的监听,Calculate按钮设置了点击后的计算逻辑。
阅读全文