I am trying to create a simple calculator which provides the EditText for the users to input the numbers.
The allowing input content should be [1,2,3,4,5,6,7,8,9,0,.]
I know that it is possible to limit the input content by using following code
android:digits="1234567890."
android:inputType="phone"
But how can I prevent the users from adding more than one dot (.
) into the EditText Box?
You can use this digits attribute android:digits="0123456789"
You can use InputFilter limit characters in an EditText as:
EditText mEdit = (EditText)findViewById(R.id.mEdit);
InputFilter[] filters = {new AdnNameLengthFilter()};
mEdit.setFilters(filters);
public static class AdnNameLengthFilter implements InputFilter
{
private int nMax;
public CharSequence filter (CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
{
Log.w("Android_12", "source("+start+","+end+")="+source+",dest("+dstart+","+dend+")="+dest);
if(dest.toString()=="."||( source.toString()==".")
{
//DO SOMTHING HERE
}else
{
//DO SOMTHING HERE
}
}
}
Second Option is TextWatcher for finding char input by user as:
mEditText = (EditText)findViewById(R.id.ET);
mEditText.addTextChangedListener(mTextWatcher);
TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
// YOU STRING BEFORE CHANGE
}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
// CHARS INPUT BY USER
}
@Override
public void afterTextChanged(Editable s) {
// AFTER TEXT CCHANGE In EDITTEXT BY USER
}
};
Use TextWatcher to check each thing as it is entered and determine whether it should be allowed into the EditText or ignored.
Make yourself one and override its methods to implement whatever logic you want.
once you create your TextWatcher apply it to the EditText like this:
edt.addTextChangedListener(mTextWatcher);