how to allow only specific number in edittext? - android

am trying to put only a specific value in my edit text.
I have used this this my layout.
android:digits="0123468"
however, i also do not want that number 1 and 3 should work in my edit text.
Sample; enter 32... it gives me a list of items
but enter 3 should not allow me to do something.
Can someone help me on this?

This could be an aproach:
<EditText
android:id="#+id/edtNumber"
android:digits="0123456789"
android:inputType="number" />
And if you want to discard '1' and '3' you could get input number like this:
Integer.parseInt(edtNumber.getText().toString())
and compare it with values you don't want.
Also if for some reason you want to use decimals do this:
<EditText
android:id="#+id/edtNumberDecimal"
android:digits="0123456789."
android:inputType="numberDecimal" />

Use regular expressions.
#Override
public void afterTextChanged(Editable s) {
String text = s.toString();
int length = text.length();
Pattern pattern
= Pattern.compile("(?s)\\d|[024-9]{2,}");
if(length > 0 && !Pattern.matches(pattern, text)) {
s.delete(length - 1, length);
}
}

Related

How to keep a text field empty in Android?

I am new to android development , i am trying to develop an app where user can keep a few text field empty,
However when user doesn't provide any input in the text field app crashes.
How do we handle empty text field in android
Following is my code for text Field.
<EditText
android:layout_width="40dp"
android:layout_height="40dp"
android:inputType="number"
android:ems="10"
android:id="#+id/editText1"
android:layout_weight="1"
android:background="#ffb7ffbf"/>`
java code:
TextView t1 = (TextView)findViewById(R.id.editText1);
a1 = Integer.parseInt(t1.getText().toString());
you should cast EditText instead of TextView.
EditText t1 = (EditText)findViewById(R.id.editText1);
Ensure if the TextBox is not empty before parsing the value to the int as
if (e.length()>0) {
int a1= Integer.parseInt(e.getText().toString());
}
Else you can get a java.lang.NumberFormatException: for Invalid int: "";
Try this:
TextView t1=(TextView)findViewById(R.id.editText1);
String aux = t1.getText.toString();
if(aux.length() > 0)
a1= Integer.parseInt(aux);
else
// the text is empty
getText.toString will bring you something always so it can be and string size 0, wich is empty. that will make the parseInt() throw an error because it won find a number in the string.
So you have to ask if the length of the string > 0, before the parse.

Format Android EditText to specific pattern

I need the user to enter text in an EditText according to this specfic pattern:
123.456-7890-123.456
The user can input any number of integers, so they could as well enter 123.456-7
I do not want the user to enter . or - just the numbers, like an input mask.
Also the numeric keyboard should only show.
I've searched StackOverflow extensively and have seen examples that use InputFilter, ChangedListener, TextWatcher but have not found anything simlar to what I'm trying to do. I've tried in various implementations of what I've found, but I'm inexperienced in using these so I may have overlooked something.
Any suggestions would be welcome.
You're going to have to use a TextWatcher and a regular expression pattern matcher to accomplish what you're trying to do.
This answer should be helpful: Android AutoCompleteTextView with Regular Expression?
You can create your own class that implements InputFilter. Then you would apply it as follows:
MyInputFilter filter = new MyInputFilter(...);
editText.setFilters(new InputFilter[]{filter});
Refer to the docs for how InputFilter is intended to work, then refer to the source code for some of the InputFilters used in Android for some ideas how to implement them.
After many failed attempts to implement InputFilter or Regular Expressions I opted for something a little more straight forward:
public void onTextChanged(CharSequence s, int start, int before, int count) {
String a = "";
String str = id.getText().toString();
String replaced = str.replaceAll(Pattern.quote("."),"");
replaced = replaced.replaceAll(Pattern.quote("-"),"");
char[] id_char = replaced.toCharArray();
int id_len = replaced.length();
for(int i = 0; i < id_len; i++) {
if(i == 2 || i == 12) {
a += id_char[i] + ".";
}
else if (i == 5 || i == 9) {
a += id_char[i] + "-";
}
else a += id_char[i];
}
id.removeTextChangedListener(this);
id.setText(a);
if(before > 0) id.setSelection(start);
else id.setSelection(a.length());
id.addTextChangedListener(this);
}
I don't know if this is the best approach but it does work. One problem I still haven't solved is how to handle cursor placement after the user deletes or inserts a number. If the user inserts the cursor somewhere in the EditText and enters a new number the cursor jumps to the end of the EditText. I would like the cursor to stay where it is at. Another problem if the user inserts the cursor within the EditText number and backspaces to delete a number, then the first key entry doesn't work and on the second key the number is entered. I can only guess this has to do with focus?
Use this: https://github.com/alobov/SimpleMaskWatcher.
Just set your mask for this watcher (###.###-####-###.###). It will add special symbols automatically and wont check your input string for being complete.
But showing the numeric keyboard you must handle by your own using android:inputType="number" tag for your EditText.

Android Signed EditText

I need use numberSigned EditText.
EditText works but i have a problem with entering numbers with a minus.
Take a number in this way:
charsEntered = Integer.parseInt(et.getText().toString());
Numbers without minus works ok but when i need enter for example -3 it don't works.
Use in your XML layout the following :
<EditText
....
android:inputType="numberSigned" />
Try following to get signed number
String tmpstr = et.getText().toString();
charsEntered = Integer.parseInt(tmpstr);
if(tmpstr.charAt(0).equals("-")) {
charsEntered *= (-1) ;
}

how do i ignore/use a carriage return in android

I am attempting to collect data from a user in the form of an edittext. The user will input a string and click a button to perform the action below:
public String encode(String s){
String result = "";
String element = "";
HashMap<String, String> translate = new HashMap<String, String>();
//initializing translate
translate.put("A",".-");
translate.put("B","-...");
translate.put("C","-.-.");
translate.put("D","-..");
translate.put("E",".");
translate.put("F","..-.");
translate.put("G","--.");
translate.put("H","....");
translate.put("I","..");
translate.put("J",".---");
translate.put("K","-.-");
translate.put("L",".-..");
translate.put("M","--");
translate.put("N","-.");
translate.put("O","---");
translate.put("P",".--.");
translate.put("Q","--.-");
translate.put("R",".-.");
translate.put("S","...");
translate.put("T","-");
translate.put("U","..-");
translate.put("V","...-");
translate.put("W",".--");
translate.put("X","-..-");
translate.put("Y","-.--");
translate.put("Z","--..");
translate.put("1",".----");
translate.put("2","..---");
translate.put("3","...--");
translate.put("4","....-");
translate.put("5",".....");
translate.put("6","-....");
translate.put("7","--...");
translate.put("8","---..");
translate.put("9","----.");
translate.put("0","-----");
s = s.toUpperCase();
for(int i=0; i < s.length();i++)
{
element = (String) translate.get(String.valueOf(s.charAt(i)));
if(element == null)
result += String.valueOf(s.charAt(i));
else
result += element;
}
return result;
}
If the user hits "enter" on the keyboard of the phone it will insert a newline / carriage return. How can I address this so that it does add a new line? I wouldn't mind using the carriage return as a way to issue the command to change focus OUT OF the edittext area, but if not that then just not allow it to be used at all.
You should use android:singleLine="true" in your EditText's XML tag, like this:
<EditText
android:id="#+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
/>
This will make the enter button change the focus to the next view in your UI, rather than inserting a new line in your EditText.
I would put this in the comments but I think my reputation is still not high enough to add comments.
Since android:singleLine="true" is now deprecated, another option is to use android:inputType="text". It's a slight change to #Tiago_Pasqualini's answer:
<EditText
android:id="#+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
/>
This too will make the enter button change focus to the next view in the UI and skip entering a new line into the EditText.

condition check for enter number would be betwen 0 to 9 0r decimal "."

i have a edit text box in which i can enter alphanumeric charracter but when i click the summit button then a checking would be perform for either edit text contains values 0 to 9 and also it can contain "." and in other case it will show a message that "pls enter numeric values" so how to achive it?
means validate 0123456789 and "." in edit textbox
public void onClick(View arg0) {
String Ammount =
((EditText) findViewById(R.id.price))
.getText().toString();
double db = Math.ceil(Integer.parseInt(Ammount)*100)/100;
ammount = Double.toString(db);
}};
Why to go hard just don't allow to enter string in your xml add:
<EditText
....
android:inputType="numberDecimal"
...
/>
add this tag in its xml android:numeric = "decimal"
One of the option would be use regex. Show the error message when validate return false.
boolean validate(String s )
{
return s.matches("[0-9\\.]*");
}

Categories

Resources