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.
Related
Need help parsing, I have tried "porting" my dice roller project to Android using Android Studio, I have most of the controller values replaced with their android widget counterparts, one problem, I am not sure how to properly parse widget values to an Int. I have marked them with aligned left comments below.
modifier is an EditText
result is a TextView
I have tried many combinations and this is the most recent.
The one that worked when it was pure java was .getValue().toString().trim() but I cannot use .getValue why is this?
public void onStart()
{
super.onStart();
percentile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v)
{
{
//issue is here
int total = Nat20_core.roll10(cumulative.isChecked(),
Integer.parseInt (String.valueOf(modifier)),
Integer.parseInt(String.valueOf(result)));
//end issue
result.setText(String.valueOf(total));
}
}
});
}
I have also tried this in a previous program as
set
This is because there is no .getValue() method for EditText and TextView widget.
For EditText, you can use getText() which returns an Editable. So, you need to get the string from it using toString(). So, you will need to use:
modifier.getText().toString();
For TextView, you can use getText() which returns a CharSequence. You also need to get the string from it using toString(). So, you can use the above line too:
result.getText().toString();
Now, you need to convert the following code:
int total = Nat20_core.roll10(cumulative.isChecked(),
Integer.parseInt (String.valueOf(modifier)),
Integer.parseInt(String.valueOf(result)));
to:
int total = Nat20_core.roll10(cumulative.isChecked(),
Integer.parseInt (modifier.getText().toString()),
Integer.parseInt(result.getText().toString()));
In EditText and TextView, the "value" is "text":
Integer.parseInt(modifier.getText().toString())
I'm writing an app that takes in an input from the AddBook class, allows it to be displayed in a List, and then allows the user to Search for their book. To this end, I'm creating a temporary EditText, binding it to the box where the user actually enters their search value, then (after ensuring that it is not empty) I compare what they've entered for the ISBN number with the ISBN numbers of each entry in the arrayList of <Book> custom objects, the list being named books.
Problem is, when I try to parse the EditText into an Int, it doesn't seem to work. I first tried using toString() on the EditText, then using Integer.parseInt() on the result of that method, but it hasn't worked out, as the conversion is seemingly unsuccessful;
All of the resources are in place and the code compiles properly, so those aren't the problems here.
EditText myEdTx = (EditText) findViewById(R.id.bookName);
if(myEdTx.getText().equals("")){Toast toast = Toast.makeText(this, "Please enter something for us to work with!", Toast.LENGTH_SHORT);
toast.show();}
else{
//resume here
for(int i=0; i<books.size(); i++)
{
Book tBook = new Book(i, null, null); tBook = books.get(i); String s=myEdTx.toString();
int tInt = Integer.parseInt(s);`
To get the string representation of an EditText's content, use:
String s = myEdTx.getText().toString();
Using toString() directly on the EditText gives you something like:
android.widget.EditText{40d31450 VFED..CL ......I. 0,0-0,0}
...which is clearly not what you want here.
You assume the user inputs a number into the text field, but that is unsafe, as you only get a string text (which theoretically can contain non-numbers as well). When I remember correctly, you can adjust a text field in android where a user only can input numbers, which should suit you more.
NumberFormatException occurs when Integer.parse() is unable to parse a String as integer, so, its better to Handle this exception.
String s = myEdTx.getText().toString();
try {
int tInt = Integer.parseInt(s);
} catch( NumberFormatException ex ) {
//do something if s is not a number, maybe defining a default value.
int tInt = 0;
}
So the current String here you are trying to parse is with white space in the line
and integer class unable to parse that white space. So use following code.
String s=myEdTx.getText().toString();
int tInt = Integer.parseInt(s.trim());
String s = myEdtx.getText().toString().trim();
int iInt = Integer.parseInt(s);
I am building a small Android app where the user will enter an IP address or a hostname into an EditText widget. 90% of the time they will be entering an IP address, the rest of the time - a hostname.
So naturally, I want to make it easy for them to enter an IP address, but the ability to switch to alpha numerics for hostname entry is important.
I can't seem to find a good inputType. The numberDecimal initially seemed like a good shot, but it only allows one dot.
Ideally, I'd like to start with a standard keyboard that had the ?123 button pressed.
How do I get there?
Try using android:inputType="number", but also set android:digits="0123456789.". Works for me.
If you use inputType="phone" you gain access to a cut down keyboard containing Numbers and a Period character - this doesn't restrict the input with regards to the amount of Periods you can enter.
Please see this answer for validation while being entered.
This works perfectly keyboard with numbers and decimal by adding android:inputType="number|numberDecimal" and android:digits="0123456789."
Example
<EditText
android:id="#+id/ip_address"
android:inputType="number|numberDecimal"
android:digits="0123456789."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
You can use your own input filter for that
final EditText text = new EditText(ServerSettings.this);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
#Override
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{1,3}(\\." +
"(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i=0; i<splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
return "";
}
}
}
}
return null;
}
};
text.setFilters(filters);
use this :
<EditText
android:id="#+id/txtIP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="0123456789."
/>
<EditText
android:id="#+id/ip_address"
android:inputType="number|numberDecimal"
android:digits="0123456789."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
worked for me
I think your only option is..
EditText android:inputType="text" ... />
You could possible check the Text for 3 dots a IP address contains
I think you need to use TextWatcher for validation, register it with TextView.addTextChangedListener() method and use Pattern.DOMAIN_NAME and Pattern.IP_ADDRESS (Android 2.2+).
See:
Android: How can I validate EditText input?
Validating IP in android
You can extend the DigitsKeyListener (source) and change the filter() function (validation that will check either ip pattern or a string hostname) and getInputType() to return InputType.TYPE_CLASS_PHONE;
Maybe if you use 2 radiobutton, one shows an edittext for host, the other one shows 4 numeric edittext for IP, then, once the user submit data you concat all 4 edittext values with dots between them, something like this, edittext1.getText() + "." + edittext2.getText() + "." edittext3.getText() + "." edittext4.getText() so you can obtain a validated IP address like that but obviously it will imply more work.
Here is the code that allows you to display a soft keyboard with only numbers and a dot (but allows you to enter multiple dots).
etIpAddress.setInputType(InputType.TYPE_CLASS_NUMBER);
etIpAddress.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
etIpAddress.setKeyListener(DigitsKeyListener.getInstance(false,false));
etIpAddress.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
SKTs answer is working pretty well until the InputFilter passes Spannables. Spannables are tricky to handle which is described for example ins answers of this question. In this case, returning "" for invalid input will replace the whole text by an empty string. I've adapted the solution also to handle this case. Here is the code, differing the types, in Kotlin:
val ipAddressFilters = arrayOf(InputFilter { source, start, end, dest, dstart, dend ->
if (end > start) {
val toCheck = if (source is Spannable) {
source.toString()
} else {
val destString = dest.toString()
destString.substring(0, dstart) + source.subSequence(start, end) + destString.substring(dend)
}
if (!toCheck.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?".toRegex())) {
return#InputFilter if (source is Spannable) { dest } else { "" }
} else {
val splits = toCheck.split("\\.".toRegex()).toTypedArray()
for (i in splits.indices) {
if (splits[i] != "" && Integer.valueOf(splits[i]) > 255) {
return#InputFilter if (source is Spannable) { dest } else { "" }
}
}
}
}
null
})
Try using android:inputType="textUri". It works especially well when you want hostname or IP address.
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.
what's the best way to mask a EditText on Android?
I Would like my EditText to behave like this decimal number input here.
Is there a easy way to do this?
You have to programmatically set an InputFilter on your EditText by setFilters.
From the documentation:
InputFilters can be attached to Editables to constrain the changes that can be made to them.
You can even change the users input, for example by adding a decimal point which is what you want if I get you correctly.
I built a decimal mask for an edit text that will auto change the edit text to the number of decimal places you want. Bascially, you listen for text changes and loss of focus.
private void formatNumber() {
sNumberToFormat = etNumberToFormat.getText().toString();
sDecimalMask = etDecimalMask.getText().toString();
boolean periodMask = false;
String delimiter = getDelimiter();
String[] decimalMask = getsDecimalMask();
if (decimalMask.length == 1) {
return;
} else {
if (delimiter.equalsIgnoreCase(",")) {
//decimal format only currently works with dot delimiters.
sDecimalMask = sDecimalMask.replace(",", ".");
}
DecimalFormat df = new DecimalFormat(sDecimalMask);
df.setRoundingMode(RoundingMode.UP);
sNumberToFormat = df.format(Float.valueOf(sNumberToFormat.replace(",", ".")));
//if (maxNumber > Float.valueOf(sNumberToFormat)) {
if (delimiter.equalsIgnoreCase(",")) {
sNumberToFormat = sNumberToFormat.replace(".", ",");
}
etNumberToFormat.setText(sNumberToFormat);
}
}
The complete demo is here.
I think you can use:
android:numeric="decimal"
on your EditText