我一直在尝试使用两个OnClickListeners,但我无法弄清楚如何正确使用它。
有人可以帮我修改我的代码吗?
btnClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramView) {
numBase.getText().clear();
numNikotin.getText().clear();
}
btnAdd.setOnClickListener(new View.OnClickListener() { // I basically want this onClick Listener for the btnClear aswell, but I just cant get both to work. If I take away the btnClear setOnCLickListener Event then btnAdd works just fine.
public void onClick(View v) {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
}
});
}
}
答案 0 :(得分:4)
不,你不能那样做。只需将两个按钮之间的共享代码拆分为另一个方法,然后在两个侦听器内部调用。
private foo() {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
btnClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramView) {
numBase.getText().clear();
numNikotin.getText().clear();
foo();
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
foo();
}
});
答案 1 :(得分:1)
试试这个,
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
numBase.getText().clear();
numNikotin.getText().clear();
btnAdd.performClick();
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
});
答案 2 :(得分:0)
试试这个 使用 performClick()
<强>
public boolean performClick ()
强>在API级别1中添加
调用此视图的OnClickListener(如果已定义)。
调用此视图的OnClickListener(如果已定义)。执行与单击相关的所有正常操作:报告辅助功能事件,播放声音等
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnAdd.performClick();
numBase.getText().clear();
numNikotin.getText().clear();
}
});
为btnAdd
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
});