Issue
I am coding a calculator in java/android studio, and I ran into this problem of only requiring one decimal point per number. Like 1.2 and not 1.2.3. The user is allowed to use fractional numbers or natural numbers in the calculator, however, once the user presses dot (“.”) sign, this cannot be repeated again for that specific number.
I coded it to show error (which didn't work), and instead of showing error, the user shouldn't be able to add another decimal point after the first one for the number. It need to work for 1.1 + 1.1 but not for 1.1.1. or 1.1. etc
I tried this as part of the code but it doesn't work. Like, it keeps disabling my equal button even though I had already written it right after the first warning.
Pattern p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
p = Pattern.compile("(\\d*(\\.\\d*)?([+\\-*%\\]|$))*");
UserInput = findViewById(R.id.ed_calculation_input);
UserInput.setShowSoftInputOnFocus(false);
tvCalculationOutput = findViewById(R.id.tv_calculation_output);
edUserInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Matcher m = p.matcher(edUserInput.getText().toString());
if(!m.matches()) {
edUserInput.setError("Enter valid no");
btnEqual.setEnabled(false);
} else {
btnEqual.setEnabled(true);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
Solution
The solution to this problem is fairly simple. You have chosen an EditText as the input for the numbers, haven't you? Then all you have to do is add the line
<EditText
...
android:inputType="numberDecimal"
...
/>
in the xml layout file which prevents a number from having multiple decimal points (or letters or other symbols).
Answered By - Cloverleaf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.