Created
November 21, 2015 21:26
-
-
Save codeasashu/38d6eb697a91731d3aeb to your computer and use it in GitHub Desktop.
This gist provides means to limit numeric range on edittext
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test; | |
import android.text.InputFilter; | |
import android.text.Spanned; | |
public class InputFilterMinMax implements InputFilter { | |
private int min, max; | |
public InputFilterMinMax(int min, int max) { | |
this.min = min; | |
this.max = max; | |
} | |
public InputFilterMinMax(String min, String max) { | |
this.min = Integer.parseInt(min); | |
this.max = Integer.parseInt(max); | |
} | |
@Override | |
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { | |
try { | |
int input = Integer.parseInt(dest.toString() + source.toString()); | |
if (isInRange(min, max, input)) | |
return null; | |
} catch (NumberFormatException nfe) { } | |
return ""; | |
} | |
private boolean isInRange(int a, int b, int c) { | |
return b > a ? c >= a && c <= b : c >= b && c <= a; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
EditText et = (EditText) findViewById(R.id.myEditText); | |
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")}); | |
.. | |
//Remember to set edittext to type "numeric" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment