Show only English characters when editing text in EditText in Android - java

I have 3 languages on my keyboard in android device and I want to show only English language letters and numbers when starting to edit text inside EditText like username field , I tried to use this line in xml file for Edittext but without any result.
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"

the best way is to use inputfilter and set it to your editText you can see a workaround to do that here :
How do I use InputFilter to limit characters in an EditText in Android?
also i found a code snippet to this like below:
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 (!isEnglishOrHebrew(source.charAt(i))) {
return "";
}
}
return null;
}
private boolean isEnglishOrHebrew(char c) {
. . .
}
};
edit.setFilters(new InputFilter[]{filter});

Related

how to avoid editing specific character in a edit text

I have a string like this 08:12:01,868 -> hour:minute:second,millisecond
now I need to edit this, I must give an option to edit first two character skip one for : then allow edit next two character again skip : and so on.
Currently I'm achieving this with lot of logic behind. I have four edit text and I'm splitting the string, then loading values in 4 edit texts and retrieving it. After joining all the edited sub strings I'm saving the value in DB.
Is there any other better way to achieve this.
I mean I'll load the string in only one edit text, Then I should be able to lock specific characters like lockFromEditChar(":",",") and remaining values can be edited with default value zero if they clear all the character.
Is it possible ? or any other best alternatives ?
The technique is called Masking. Create this class MaskWatcher like this
import android.text.Editable;
import android.text.TextWatcher;
public class MaskWatcher implements TextWatcher {
private boolean isRunning = false;
private boolean isDeleting = false;
private final String mask;
public MaskWatcher(String mask) {
this.mask = mask;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
isDeleting = count > after;
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
if (isRunning || isDeleting) {
return;
}
isRunning = true;
int editableLength = editable.length();
if (editableLength < mask.length()) {
if (mask.charAt(editableLength) != '#') {
editable.append(mask.charAt(editableLength));
} else if (mask.charAt(editableLength-1) != '#') {
editable.insert(editableLength-1, mask, editableLength-1, editableLength);
}
}
isRunning = false;
}
}
and than use your edittext like this
editText.addTextChangedListener(MaskWatcher("##:##:##,###"));
If you have the cursor blocked in the last position and longClick disabled(copy paste):
Note that this example works only for strings, no spans
Create a TextWatcher and auto add : and , when you detect a new character added and the new size is 2,4(for ':'),6(for ',').
Also detect when you delete a character and the current size is 2,4,6, you have to delete the character before ';' or ',' as well.
class Watcher(private val textView:TextView) : TextWatcher {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val text = s?.toString()?:""
val isDelete = textView.length > text.size
if(isDelete) {
//you can change this to an if to check for 2,4,6 and use take(size-1)
newString = when(text.size) {
2->text.take(1)
4->text.take(3)
6->text.take(5)
}
if(newString!=null) {
textView.text = newString
}
} else {
newString = when(text.size) {
2,4 -> text + ":"
6 -> text + ","
}
if(newString!=null) {
textView.text = newString
}
}
}
}

Limit Decimal Places in EditText

I'm using an EditText Field where the user can specify an amount of money.
I set the inputType to numberDecimal which works fine, except that this allows to enter numbers such as 123.122 which is not perfect for money.
I wrote some custom InputFilter method and it's working like this .User can 5 elements before dot and after dot-two,but not working correctly
My goals are :
1) use should input maximum 9999.99
2) If user starting from 0 and second element is also 0,It must replace with .(for example 0.0) and after two elements after dot(like this 0.01)
here is a my code
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
mPattern=Pattern.compile("[0-9]*" + (digitsBeforeZero-1) + "}+((\\.[0-9]*" + (digitsAfterZero-1) + "})?)||(\\.)?");
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher=mPattern.matcher(dest);
if(!matcher.matches())
return "";
return null;
}
}
I'm calling this method like this
amountValue.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
How I can rewrite my code to solved my issues ?
thanks
Your constructed regex is all wrong.
The first part of your regex is this expression:
"[0-9]*" + (digitsBeforeZero-1) + "}+"
Say digitsBeforeZero = 5, that gets you:
[0-9]*4}+
That's not the correct regex. The regex is supposed to be:
[0-9]{1,5}
meaning between 1 and 5 digits.

How to limit the EditText input only allow 3 digits of number either integer or decimal

As the title says, I set up an EditText in my activity and want to limit the input to only numbers. However, it doesn't matter if it is a decimal number or integer. I do require the number of digits is limited at 3. For example, the input of '123', '1.23', '12.3' are all legit input.
'1234', '123.', '.123' are all illegal input.
I have tried to set up
android:inputType = "numberDecimal"
in the xml file.
And set the max length to 4.
edit:
I also tried following code:
InputFilter filter = new InputFilter() {
//^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$
//^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
// adding: filter
// build the resulting text
String destinationString = dest.toString();
String resultingTxt = destinationString.substring(0, dstart) + source.subSequence(start, end) + destinationString.substring(dend);
// return null to accept the input or empty to reject it
return resultingTxt.matches("^\\-?(\\d{0,3}|\\d{0,2}\\.\\d{0,1}|\\d{0,1}\\.\\d{0,2})$") ? null : "";
}
return null;
}
};
I did modified the regex from the sample code mentioned by #Suman Dash.
My understanding of the regex
^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$
is to allow certain pattern of number input such as #.##, ##.# and ###.
When I test the code, the pattern #.## and ##.# are working fine, but the pattern ### also allow input like ".##", for example, ".88" as legit input. And it treats the decimal point as a legit number, so I can only input ".88", not ".123". Anyway, I don't want any number starts with the decimal point.
How can I eliminate that?
What's the best way to achieve this goal? Thanks!
InputFilter filter = 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 (!Pattern.compile("[1234567890\.]*").matcher(String.valueOf(source.charAt(i))).matches())
{
return "";
}
}
return null;
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText ntxt =(EditText)findViewById(R.id.numberEditTextbox) ;
ntxt.setFilters(new InputFilter[]{filter,new InputFilter.LengthFilter(4)});
}
This code may help you.

android EditText maxLength not working

This is my xml
<EditText
android:id="#+id/et_comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textNoSuggestions|textVisiblePassword"
android:hint="Provide comments here..."
android:gravity="top"
android:maxLength="5"
android:textSize="12sp"
android:visibility="visible"
/>
Neither is it working using this code
TextView editEntryView = new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(5);
editEntryView.setFilters(filterArray);
maxLenth is not working, I dont know why, but it isnt.
I have checked other answers on the stack but they are also not working.
Please check if any of EditText attributes are conflicting or what is the problem?
EDIT: Same problem is being faced by other developers
See comments here same problem is being faced by Mansi and aat
And here in comments same problem is being faced by Vincy and Riser
EDIT: Problem solved
I was using input filter which overrides the max length in xml making it not able to work.
The reason input filter didn't worked for me was that I was using another input filter which overwrites the previous maxLength input filter.
Making it into a single input filter fixed that issue for me.
Try this, it will work for both maxlenght and input filter
month.setFilters(new InputFilter[]{new InputFilterMinMax("0", "12"), new InputFilter.LengthFilter(2)});
If you are using InputFilter for the edittext, then maxLength will not work.
Fairly old post but, I noticed how the XML is an actual EditText object, while you are adding the filters to a TextView which could handle it differently than EditText. If you are adding an InputFilter object manually, the xml property is overridden.
The example code on which you add InputFilters to the View seems to be a TextView object. Make sure you pull the right view and it's being cast to EditText if you go with the manual addition of the filters--it's working for me right now.
Good luck.
If you already have InputFilter then maxLength will not work. You will have to create an additional InputFilter and add it:
// Filter for comma character
String blockCharacterSet = ",";
InputFilter filter = (source, start, end, dest, dstart, dend) -> {
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
return null;
};
// Filter for max Length
InputFilter filter1 = new InputFilter.LengthFilter(20);
// Set the filters
et_list_name.setFilters(new InputFilter[] { filter, filter1 });
If you are using InputFilter for the edittext, then maxLength will not work.
It's correct if you add a filter with replacing original filters.
You can use android:maxLength="5" in your xml.
And in your code just add a filter without replacing existed filters.
Kotlin:
editText.filters = arrayOf(
*editText.filters,
InputFilter.AllCaps(), // your filter
// other filters
)
To add character restriction as well as input limit.
private String BlockCharacterSet_Name = "\\#$#!=><&^*+\"\'";
mFirstName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(25),inputFilter_Name});
private InputFilter inputFilter_Name = new InputFilter() { //filter input for name fields
#Override
public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
if (charSequence != null && BlockCharacterSet_Name.contains(("" + charSequence))) {
return "";
}
return null;
}
};
{new InputFilter.LengthFilter(25),inputFilter_Name}
allows you to set both max length limitation as well as your special characters restrictions both in the same InputFilter and therefore you dont need to create separate Inputfilter for the same.
Try this:
val existingFilters: Array<InputFilter> = editText.filters
editText.filters = existingFilters.apply { plus(filter) }
You need to get the list of existing filters like maxLength applied through XML and then add more filters to it. In your case, the maxLength property of the editText was overridden by the custom InputFilter you were trying to apply.
In my case DataBinding is used, but someone changed filter right in code using ViewBinding.
binding.edit_text.filters = arrayOf<InputFilter>(object : InputFilter {
override fun filter(
source: CharSequence?,
start: Int,
end: Int,
dest: Spanned?,
dstart: Int,
dend: Int
): CharSequence {
return source.toString().filter { it.toString().matches(("[${LETTERS}]").toRegex()) }
}
})
Android Studio didn't find what method referred to "#+id/edit_text" until I removed that id from the EditText.

Limit EditText to text (A-z) only

I want an editText that only allows text input from A to z, no numbers or other characters. I've found out I have to use InputFilter but I don't understand how this code works.
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))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
The code you posted adds a custom filter to the EditText field. It checks to see if the character entered is not a number or digit and then, if so, returns an empty string "". That code is here:
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
For your needs, you want to change the code slightly to check if the character is NOT a letter. So, just change the call to the static Character object to use the isLetter() method. That will look like this:
if (!Character.isLetter(source.charAt(i))) {
return "";
}
Now, anything that is not a letter will return an empty string.
Haven't actually done it, but check Androids NumberKeyListener. You can find the source code for it here:
http://www.java2s.com/Open-Source/Android/android-core/platform-frameworks-base/android/text/method/NumberKeyListener.java.htm
it does exactly the opposite of what you need, but that should be a good enough starting point.

Categories

Resources