Android : How to set acceptable numbers and characters in EditText? - android

I have to set acceptable characters "0123456789" and "semicolon" in the EditText. Below is the code I'm using.
android:digits="0123456789;"
android:inputType="number|text
The problem with that implementation is in HTC phones, semicolon can't be entered but in Samsung and Sony Ericsson, semicolon can be entered. Another problem is when I entered semicolon in Samsung and Sony Ericsson, semicolon can't be deleted. Is there any missing property in the above code? Thanks in advance.

Android provides an easy way to edit text fields by modifying the layout xml and adding an android:inputType="text". This lets you easily create some basic validations like numbers, decimal, phone or emails. But there's no parameter for alphanumeric (i.e. no special characters). To do this, you need to use an input filter like below and set the fields you want to validate with that filter in code. This input filter
InputFilter alphaNumericFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence arg0, int arg1, int arg2, Spanned arg3, int arg4, int arg5)
{
for (int k = arg1; k < arg2; k++) {
if (!Character.isLetterOrDigit(arg0.charAt(k))) {
return "";
} //the first editor deleted this bracket when it is definitely necessary...
}
return null;
}
};
mFirstName.setFilters(new InputFilter[]{ alphaNumericFilter});

To limit what the user can enter as they type use a TextWatcher, discussed in this question Android: How can I validate EditText input?.
Better yet: Allow only selected charcters based on regex in an EditText

The solution is to modify the these fields: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputMethod
Set the InputMethod of the EditText so that you can properly get what you need.

Here is the regular expression
Pattern mPattern = Pattern.compile("^([1-9][0-9]{0,2})?(\\.[0-9]?)?$");
Matcher matcher = mPattern.matcher(loginNameString.toString());
if(!matcher.find())
{
//TODO
}

Related

how to remove special characters when i paste +1-xxx-xxx-xxxx from another source in android edit text with 10 digits length in android

copy from another source is : +1-541-xxx-3010
when i paste in my edit text i need to get the result as follow :
541xxx3010
need to remove special characters and also need to remove +1 (country code)
i need to display only 10 digits actual number after removing special chars
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){
String edit = s.toString();
System.out.println("##"+edit);
edit = edit.replaceAll("[^0-9]", "");
String result = edit.replaceAll("[|?*<\":>+\\[\\]/'-]","");
System.out.println(result);
}
You can try SubString to get only 10 digit from your string.
For E.g. Your String is +1-541-xxx-3010. Now as you want you need to remove the + and country code.
String phone = "+1-541-xxx-3010"
result = phone.substring(Math.max(phone.length() - 12, 0)).replaceAll("-", ""));
From the above code it returns the result like this.
Result: 541xxx3010
NOTE : Before apply this code you need to check if your string is not
empty or its size is greater than or equal 12.
OR
If you don't want to use + and - then why don't you restrict the character using android:digits just apply below property in edittext.So it will not allow to enter the character apart from 0-9.
android:digits="0123456789"
First you need to remove country code from the string using substring() method,
For remove special character in your case it is "-" you can refer below code snippet
String result = inputString.replaceAll("[-]","");

EditText with input type = number , how to show user ":"

So, I want user to write two numbers divided by this symbol ":" in EditText. I've added TextWatcher to this EditText, so I can see what user is typing.
Thus, that's what I have in my Watcher in afterTextChanged.
#Override
public void afterTextChanged(Editable s)
{
String textToEdit = s.toString();
if (s.length()==2)
{
String h = s.toString();
h = h+":";
edit.setText(h);
edit.setSelection(edit.getText().length());
}
}
When user type more than 2 digits, I'm adding ":" to EditText.
And here I have problem.
Input type of this EditText is "number",
so, only numbers can be there and ":" is not a number.
Little example:
User typed 24. afterTextChanged get it and add set "24:".
24 was a number , "24:" is a string.
So, now I have "24:" and when I try to delete something from EditText I get fatal error.
Is there any other way to show ":" in my EditText? Or what I'm doing wrong?
Try putting android:digits="0,1,2,3,4,5,6,7,8,9,:" in the xml of the EditText
*Edit:
this might be android:digits="0123456789:" actually :p

How i can Detect type of language in a string?

I have a SMS counter that count typed character;
I wanna when user type English char(English chars + sings + numbers) ,counting Variable do ++ to Number: 160,
But , if in all there r a Persian char , counting Variable do ++ to Number: 70
what I should to do?
I Fined that this code : var ucs2 = text.search(/[^\x00-\x7D]/) in php return What character user ; Persian char or English.
The equivalent code in Java - What is Android؟
private final TextWatcher TextWatcher_Method = new TextWatcher()
{
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
cnt2=matn_counter.length();
TextView counter=(TextView)findViewById(R.id.txt_counter);
cnt1=(int) Math.ceil(cnt2/6);
Integer cnt3=(cnt2%6);
counter.setText(Integer.toString(cnt1)+"/"+Integer.toString(cnt3));
}
}
You can use Bidi class.
for more info look at this answer please.
You can't send 'real' SMS from emulator to device, because you don't have a SIM card.
You can, however, send it from emulator to emulator if you have more than one running.
To do this, check this question: Sending and receiving text using android emulator
Here's some useful tips on how to send SMS, make call, etc... http://www.apurbadebnath.com/blog/android-emulator-tips/
The Answer:
Actually you should check ASCII chars.
If any char is out of ASCII range (0x0000 to 0x007F) the message becomes to 70 length limit.
And otherwise as you motioned, if all chars is ASCII (for example English letters or numbers) the limitation on message length is 160.
the code is simple:
public static boolean isASCIIMessage(String s) {
for (int i = 0; i < Character.codePointCount(s, 0, s.length()); i++) {
int c = s.codePointAt(i);
if (c >= 0x0000 && c <=0x007F)
return false;
}
return true;
Anyway if you want detect Persian input see this answer.

Restricting Android NumberPicker to Numeric Keyboard for Numeric Input (not Alpha keyboard)

Is there a way to suggest or restrict keyboard input when selecting a NumberPicker so only the number controls are shown when entering values, similar to how you can use android:inputType="number" with a EditText?
I have a series of values, from 0.0 to 100.0 in 0.1 increments that I'd like to be able to use a NumberPicker to select in Android 4.3. In order to have the numbers selectable, I've created an array of strings which corresponds to these values, as shown below:
NumberPicker np = (NumberPicker) rootView.findViewById(R.id.programmingNumberPicker);
int numberOfIntensityOptions = 1001;
BigDecimal[] intensityDecimals = new BigDecimal[numberOfIntensityOptions];
for(int i = 0; i < intensityDecimals.length; i++ )
{
// Gets exact representations of 0.1, 0.2, 0.3 ... 99.9, 100.0
intensityDecimals[i] = BigDecimal.valueOf(i).divide(BigDecimal.TEN);
}
intensityStrings = new String[numberOfIntensityOptions];
for(int i = 0; i < intensityDecimals.length; i ++)
{
intensityStrings[i] = intensityDecimals[i].toString();
}
// this will allow a user to select numbers, and bring up a full keyboard. Alphabetic keys are
// ignored - Can I somehow change the keyboard for this control to suggest to use *only* a number keyboard
// to make it much more intuitive?
np.setMinValue(0);
np.setMaxValue(intensityStrings.length-1);
np.setDisplayedValues(intensityStrings);
np.setWrapSelectorWheel(false);
As more info, I've noticed that if I dont use the setDisplayedValues() method and instead set the integers directly, the numeric keyboard will be used, but the problem here is that the number being entered is 10 times more than it should be - e.g. if you enter "15" into the control its interpreted as "1.5"
// This will allow a user to select using a number keyboard, but input needs to be 10x more than it should be.
np.setMinValue(0);
np.setMaxValue(numberOfIntensityOptions-1);
np.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int value) {
return BigDecimal.valueOf(value).divide(BigDecimal.TEN).toString();
}
});
Any suggestions on how to raise a numeric keyboard to allow a user to enter decimal numbers like this?
I have successfully achieved this, borrowing heavily from #LuksProg's helpful answer to another question. The basic idea is to search for the EditText component of the NumberPicker and then to assign the input type as numeric. First add this method (thanks again to #LuksProg):
private EditText findInput(ViewGroup np) {
int count = np.getChildCount();
for (int i = 0; i < count; i++) {
final View child = np.getChildAt(i);
if (child instanceof ViewGroup) {
findInput((ViewGroup) child);
} else if (child instanceof EditText) {
return (EditText) child;
}
}
return null;
}
Then, in my Activity's onCreate() method I call this and set the input type:
np.setMinValue(0);
np.setMaxValue(intensityStrings.length-1);
EditText input = findInput(np);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
That did the trick for me!
My answer is to improve on the basis of Alan Moore, just change the last line
input.setInputType(InputType.TYPE_CLASS_NUMBER);
to
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
then there will no more problem like personne3000 said, no more crashes.
I'm sorry my English is not good, but I hope you can understand what I mean.

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.

Categories

Resources