[英]Android onClickListener doesn't work for second time
当用户第二次单击我的代码中名为 calButton 的按钮(具有 setOnClickListener 方法)时,它不起作用,它只显示最后的结果。 这是我的代码:
public void calculate(View view){
//Identify IDs
TextView delta = findViewById(R.id.delta);
Button calButton = findViewById(R.id.calculatebtn);
EditText textA = findViewById(R.id.editTextA);
EditText textB = findViewById(R.id.editTextB);
EditText textC = findViewById(R.id.editTextC);
TextView root1 , root2;
root1 = findViewById(R.id.root1);
root2 = findViewById(R.id.root2);
//Return text to float
float a , b , c;
a = Float.parseFloat(textA.getText().toString());
b = Float.parseFloat(textB.getText().toString());
c = Float.parseFloat(textC.getText().toString());
//Calculate DELTA
float deltaF = (b * b) - (4 * a * c);
//Set Texts and Calculate Roots
calButton.setOnClickListener(v -> {
delta.setText("Delta : " + deltaF);
delta.setAlpha(1);
if (deltaF < 0) {
root1.setText("Null");
root1.setAlpha(1);
} else if (deltaF == 0) {
float root = -b / (2 * a);
root1.setText("Root 1 : " + root);
root1.setAlpha(1);
} else if (deltaF > 0) {
if (b > 0) {
float bPosetive = (0.0f) - b;
float root1F = (float) ((bPosetive + Math.sqrt(deltaF)) / (2 * a));
float root2F = (float) ((bPosetive - Math.sqrt(deltaF)) / (2 * a));
root1.setText("Root 1 : " + root1F);
root2.setText("Root 2 : " + root2F);
root1.setAlpha(1);
root2.setAlpha(1);
} else if (b < 0) {
float bNegetive = (0.0f) - b;
float root1F = (float) ((bNegetive + Math.sqrt(deltaF)) / (2 * a));
float root2F = (float) ((bNegetive - Math.sqrt(deltaF)) / (2 * a));
root1.setText("Root 1 : " + root1F);
root2.setText("Root 2 : " + root2F);
root1.setAlpha(1);
root2.setAlpha(1);
}
}
});
}
我预计当用户编辑文本并第二次单击按钮时,它会计算输入并显示它们,但不起作用,只显示最后的输出
这是因为a
、 b
、 c
和deltaF
是原始类型。 当 EditText 值改变时,这些值不会改变。
此外,您应将代码逻辑分成不同的方法。 对于此示例, calculate()
用于计算值, initUI()
用于初始化 UI。
代码示例
public float calculate(float a, float b , float c) {
return a + b + c;
}
public void initUI() {
calButton.setOnClickListener(v -> {
EditText textA = findViewById(R.id.editTextA);
EditText textB = findViewById(R.id.editTextB);
EditText textC = findViewById(R.id.editTextC);
float a , b , c;
a = Float.parseFloat(textA.getText().toString());
b = Float.parseFloat(textB.getText().toString());
c = Float.parseFloat(textC.getText().toString());
calculate(a, b, c);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.