我正在尝试创建一个计算器应用程序,显示用户在编辑文本屏幕上单击的所有内容,但是,当用户单击按钮时,编辑文本屏幕仍然为空白。我已经写了一些印刷语句来看看会发生什么,这就是我发现的:
updateEditText()
中的print语句始终为空,即使用户单击按钮,但getValuesPressed()
中的print语句也会成功打印出单击按钮的位置。
我不明白我做错了什么。
这就是我所拥有的:
void updateEditText(){
EditText et = (EditText) findViewById(R.id.editText);
System.out.println("THE VALUE PRESSED IS: " + getValuesPressed());
et.setText(getValuesPressed());//problem here
}
//return and concat the buttons that were clicked
String getValuesPressed(){
for(int i = 0; i < buttonList.length; i++){
final int j = i;
buttonList[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("THE BUTTON WAS PRESSED: " + buttonList[j].getText());
switch(j){
case 0://CLEAR
textOnScreen = "0";
break;
case 5://SQRT
solveEquation();
//CASE: IF IT IS NEG U CANT TAKE THE SQRT!!!!
textOnScreen = String.valueOf(Math.sqrt(Double.parseDouble(textOnScreen)));
break;
case 18: //NEGATIVE
if(textOnScreen.charAt(textOnScreen.length() - 1) != '-')
textOnScreen = textOnScreen + "-";
else
textOnScreen = textOnScreen.substring(0, textOnScreen.length() - 1);
break;
case 19: //BACKSPACE
if(textOnScreen.length() == 1)
textOnScreen = "0";
else
textOnScreen = textOnScreen.substring(0, textOnScreen.length() - 1);
break;
case 20: //SOLVE
solveEquation();
break;
default://concat all of the other buttons pressed
textOnScreen = textOnScreen + buttonList[j].getText();
break;
}
}
});
}
return textOnScreen;
}
答案 0 :(得分:2)
您不应该为每个按钮多次设置OnClickListener。 将String getValuesPressed()函数更改为void setButtonClickEvents()。
此外,您不需要updateEditText()函数。 而不是连接textOnScreen,直接连接EditText:
case 0://CLEAR
et.setText("0");
break;
case 5://SQRT
solveEquation();
//CASE: IF IT IS NEG U CANT TAKE THE SQRT!!!!
et.setText(String.valueOf(Math.sqrt(Double.parseDouble(et.getText().toString())));
break;
等等。
答案 1 :(得分:1)
您的整个代码对我来说并不合理。您应该做的第一件事是为所有按钮添加onClickListener
。这个监听器看起来像这样:
@Override
public void onClick(View v) {
System.out.println("THE BUTTON WAS PRESSED: " + ((Button)v).getText();
switch(v.getId()){
case R.id.<ID of this Button>://CLEAR
et.setText("0");
break;
case R.id.<ID of this Button>://SQRT
solveEquation();
//CASE: IF IT IS NEG U CANT TAKE THE SQRT!!!!
et.setText(String.valueOf(Math.sqrt(Double.parseDouble(textOnScreen))));
break;
case R.id.<ID of this Button>: //NEGATIVE
if(et.getText().charAt(et.getText().length() - 1) != '-')
et.setText(et.getText + "-");
else
et.setText(et.getText().toString().substring(0, et.getText().length() - 1));
break;
case R.id.<ID of this Button>: //BACKSPACE
if(et.getText().length() == 1)
et.setText("0");
else
et.setText(et.getText().toString()substring(0, et.getText().length() - 1));
break;
case R.id.<ID of this Button>: //SOLVE
solveEquation();
break;
}
}