GoogleMac GoogleMac - 4 months ago 13
Android Question

How can I set an Input Filter to accept only BINARY characters (0 or 1) on Android?

Here is my current code which only allows integers. I want to restrict the user even more to only allow 0s and 1s. I wish it were as simple as

!Character.isBinary(..)
, but it isn't. How can I manipulate the start and end parameters to accomplish this?

final InputFilter binaryOnlyFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for ( int i = start; i < end; i++) {
if (!Character.isDigit(source.charAt(i)) && source.charAt(i) != ' ') {
return "";
}
}
return null;
}
};

Answer

1) If you just want 0's and 1's , add android:digits="01" in your edit text

2) If you want to add some space as well, then try this answer

stackoverflow.com/a/26057532/1852441

in that answer, just replace

if(cs.toString().matches("[a-zA-Z ]+")){ 

with

if(cs.toString().matches("[01 ]+")){