Reputation: 5027
I have recently designing for an android calculator, and the display is named fakedisplay. i am now adding a backspace button for the calculator, and the code is as follows:
backspace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearCalcDisplay = DONT_CLEAR;
String str=Fakedisplay.getText().toString();
if (str.length() >=1 ) {
str = str.substring(0, str.length() - 1);
Fakedisplay.setText(str);
};
if (str.length() <1 ) {
Fakedisplay.setText("0");
}
});
My questions are that
I have tried the above and it works for inputs longer than 1 characters, eg 145 it will give out 14, when it is 14 it gives out 1, but when further pressed, the program will be forced-close. Why?
And how to consider for decimal input?
Would there be any better codes for this function?
Upvotes: 1
Views: 16058
Reputation: 31
String str=Fakedisplay.getText().toString();
if (str.length() >1 ) {
str = str.substring(0, str.length() - 1);
Fakedisplay.setText(str);
}
else if (str.length() <=1 ) {
Fakedisplay.setText("0");
}
**I used this code in the buttonBackspace public void section **
Upvotes: 0
Reputation:
I simply did this:
void delete(EditText expr) {
String str = expr.getText().toString();
if(str.length() == 0)
return;
str = str.substring(0, str.length() - 1);
expr.setText(str);
}
And I used the xml onclick element. It worked.
Upvotes: 0
Reputation: 11
//Needed an extra closing bracket. If you don't include the 0 and just leave //"" instead you will have a blank space instead of a zero.
backspace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = Fakedisplay.getText().toString();
if (str.length() > 1) {
str = str.substring(0, str.length() - 1);
Fakedisplay.setText(str);
} else if (str.length() <= 1) {
Fakedisplay.setText("0");
}
}
});
Upvotes: 0
Reputation: 141
I combined both codes and got the perfect code
backspace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str=Fakedisplay.getText().toString();
if (str.length() >=1 ) {
str = str.substring(0, str.length() - 1);
Fakedisplay.setText(str);
} else if (str.length() <=1 ) {
Fakedisplay.setText("0");
}
});
Upvotes: 0
Reputation: 2491
change the code to
backspace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearCalcDisplay = DONT_CLEAR;
String str=Fakedisplay.getText().toString();
if (str.length() >1 ) {
str = str.substring(0, str.length() - 1);
Fakedisplay.setText(str);
}
else if (str.length() <=1 ) {
Fakedisplay.setText("0");
}
});
Upvotes: 6