I want to set a 1 character length in EditText but just in one part of condition. There is a way to set max length via XML but this will be applied for the whole condition. How to set max length programmatically?
public void setEditTextMaxLength(EditText editText, int length) {
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(length);
editText.setFilters(FilterArray);
}
You can add this in your XML:
android:maxLength="10"
or programmatically:
EditText editText = new EditText(this);
int maxLength = 3;
editText.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(maxLength)
});
In Kotlin, this extension function is handy:
fun EditText.setMaxLength(maxLength: Int) {
filters = arrayOf(InputFilter.LengthFilter(maxLength))
}
edtTime.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(4) });
i have the following problem to resolve in an Android App. I have an editText which has to show only numbers and the the letters 'x' and 'c' when the keyboard is prompted. Is this possible? Thanks for the help!
Sure you can, with filters using InputFilter.
Here a piece of sample code:
InputFilter filter = new InputFilter()
{
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) == 'x') || (source.charAt(i) == 'c'))
{
return "";
}
}
return null;
}
};
editText.setFilters(new InputFilter[] { filter });
You have to build your own keyboard or you can restrict input in such a way:
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,xc" />
try below properties for your EditText
Example :
Alphabet
android:inputType="text" // for alphabet
you can put your own combination of digits
android:digits="0,1,2,3,4,5,6,7,8,9,*,xc" // you can put your own combination of digits
Alphanumeric
android:digits="0123456789 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Numeric
input.setRawInputType(Configuration.KEYBOARD_12KEY); // its show only the numeric keyboard.
I need a edit text validation which will only allow number and : symbol.and length should not be more than 5 char.And most I am creating this edittext pragmatically
final EditText timeVisited = new EditText(this);
timeVisited.setId(20);
timeVisited.setText(Tm);
timeVisited.setTextColor(Color.BLACK);
timeVisited.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
timeVisited.setHint("eg. 14:30");
timeVisited.setPadding(5,5,5,5);
timeVisited.setSingleLine(false);
timeVisited.setLines(1);
timeVisited.setBackgroundResource(R.drawable.text_bg);
customerToCatchTblRow.addView(timeVisited);// add the column to the table row here
LinearLayout.LayoutParams params5 = (LinearLayout.LayoutParams)timeVisited.getLayoutParams();
params5.setMargins(0, 0, 5, 0); //substitute parameters for left, top, right, bottom
timeVisited.setLayoutParams(params5);
Use android:digits attribute for filtering symbols:
<EditText
android:digits="0123456789:"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
or programmatically:
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789:"));
Try this, it programmatically sets the digits allowed for the EditText for validation purpose, the alphabets/numbers/symbols can be mentioned in which the user can enter only those characters
timeVisited.setKeyListener(DigitsKeyListener.getInstance("0123456789:"));
For setting maxlength via code,
int maxLength = 5;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
timeVisited.setFilters(FilterArray);
Let me know if that worked.
use InputFilter. Code can be something like this
InputFilter filter = new InputFilter() {
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;
}
};
timeVisited.setFilters(new InputFilter[] { filter });
And to limit the lenght in xml of edittext use
android:maxLength="5"
Why are you using EditText for getting time, Use TimePicker instead.
In my application I have to validate the EditText. It should only allow character, digits, underscores, and hyphens.
Here is my code:
edittext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// validation codes here
location_name=s.toString();
Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();
if (location_name.matches(".*[^a-z^0-9].*")) {
location_name = location_name.replaceAll("[^a-z^0-9]", "");
s.append(location_name);
s.clear();
Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();
}
}
});
location.add(location_name);
When I enter input into EditText, the application is force closed.
Instead of using your "manual" checking method, there is something very easy in Android:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
for (int i = start;i < end;i++) {
if (!Character.isLetterOrDigit(source.charAt(i)) &&
!Character.toString(source.charAt(i)).equals("_") &&
!Character.toString(source.charAt(i)).equals("-"))
{
return "";
}
}
return null;
}
};
edittext.setFilters(new InputFilter[] { filter });
Or another approach: set the allowed characters in the XML where you are creating your EditText:
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed" />
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed"
/>
the above code will also include , additionally to avoid , use the following code
<EditText
android:inputType="text"
android:digits="0123456789qwertzuiopasdfghjklyxcvbnm_-"
android:hint="Only letters, digits, _ and - allowed"
/>
This can be useful, especially if your EditText should allow diacritics (in my case, Portuguese Diacritic):
<EditText
android:digits="0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÁáÂâÃãÀàÇçÉéÊêÍíÓóÔôÕõÚú"
/>
A solution similar to the android:digits="0123456789*", is to use this:
EditText etext = new EditText(this);
etext.setKeyListener(DigitsKeyListener.getInstance("0123456789*"));
An added bonus is that it also displays the numeric keypad.
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.toString(source.charAt(i)).matches("[a-zA-Z0-9-_]+")) {
return "";
edittext.setError("Only letters, digits, _ and - allowed");
}
}
return null;
}
};
edittext.setFilters(new InputFilter[] { filter });
Try this:
public static SpannableStringBuilder getErrorMsg(String estring) {
int ecolor = Color.BLACK; // whatever color you want
ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
return ssbuilder;
}
Then setError() to EditText when you want show 'only Letters and digits are allowed' as below.
etPhone.setError(getErrorMsg("Only lowercase letters and numbers are allowed!"));
Hope this will help you. I use the same for Validation Check in EditText in my apps.
please try adding the android:digits="abcde.....012345789" attribute? although the android:digits specify that it is a numeric field it does work for me to set it to accept letters as well, and special characters as well (tested on SDK-7)
You can validate this by two ways , both worked for me, hope will be helpful for you too.
1> Mentioning the chars in your edittext .
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
2> Can validate pragmatically as answered by milos pragmatically
use this 2 function
public static boolean isdigit(EditText input)
{
String data=input.getText().toString().trim();
for(int i=0;i<data.length();i++)
{
if (!Character.isDigit(data.charAt(i)))
return false;
}
return true;
}
public static boolean ischar(EditText input)
{
String data=input.getText().toString().trim();
for(int i=0;i<data.length();i++)
{
if (!Character.isDigit(data.charAt(i)))
return true;
}
return false;
}
pass Edittext variable in these function .. so you can have boolean value.
I need to set validation for a edittext view should allow two numeric values and two decimal values.
example: 22.32
Please let me know how to do this validation
Thanks in advance
Try this out. I suck at regex so it may not be the best, but give it a try.
EditText text = new EditText(this);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
if (!resultingTxt.matches("^\\d(\\d(\\.\\d{0,2})?)?")) {
return "";
}
}
return null;
}
};
text.setFilters(filters);
boolean isValid=<EditText Variable>.getText().toString().matches("\\d{2}\\.\\d{2}");
Put this method in a onClickListener and I guess you will be good to go.