Reputation: 63
I'm new in programming. I did a simple android app which ask user to put 2 numbers, do calculations, display the answer by clicking calculate button. Now I'm trying to set up reset button to clear all the fields. Checked for the solution on stack overflow, but still cannot figure out how to do it. This is my code:
public void calculate(View view)
{
EditText number1 = (EditText)findViewById(R.id.num1ID);
EditText number2 = (EditText)findViewById(R.id.num2ID);
Double num1Value = Double.parseDouble(number1.getText().toString());
Double num2Value = Double.parseDouble(number2.getText().toString());
Double resultValue = num1Value - num2Value;
TextView resultDisplay = (TextView)findViewById(R.id.resultID);
resultDisplay.setText(Double.toString(resultValue));
}
Thank you.
Upvotes: 6
Views: 739
Reputation: 39
OnClick of Reset Button set the setText of EditText to Empty Strings. You can follow the below link it is useful for beginners http://www.mkyong.com/tutorials/android-tutorial/
Upvotes: 1
Reputation: 1412
Exact code for your program.
public void calculate(View view) {
EditText number1 = (EditText)findViewById(R.id.num1ID);
EditText number2 = (EditText)findViewById(R.id.num2ID);
Button B_reset=(Button)findViewById(R.id.bReset);
// create a button on your Layout for Reset as "bReset"
Double num1Value = Double.parseDouble(number1.getText().toString());
Double num2Value = Double.parseDouble(number2.getText().toString());
Double resultValue = num1Value - num2Value;
TextView resultDisplay = (TextView)findViewById(R.id.resultID);
resultDisplay.setText(Double.toString(resultValue));
//reset code
B_reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
number1.setText(""); // reset the EditText number1
number2.setText(""); // reset the EditText number2
resultDisplay.setText(""); // reset the Textview resultDisplay
}
});
}
Upvotes: 2
Reputation: 210
Do you want reset your edittext ?
private void resetNumbersFields() {
number1.setText("");
number2.setText("");
resultDisplay.setText("");
// if you want you can add setHint to add hint to your EditText when your field is empty
}
I hope that help you
Upvotes: 2
Reputation: 2832
Have a method like this
public void resetTextViews() {
number1.setText("");
number2.setText("");
resultDisplay.setText("");
}
Then just set an on click listener on your button that calls that method.
Upvotes: 3
Reputation: 1735
There is no method in EditText to clear the data. If you want to clear the data you have to set
.setText("");
In android documentation itself there is no option to reset the field.
Upvotes: 2
Reputation: 595
Just add button resetButton to layout
Button resetButton = (Button) findViewById(R.id.btnReset);
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
number1.setText("");
number2.setText("");
resultDisplay.setText("");
}
});
Upvotes: 4