Format Android EditText to specific pattern - android

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.

Related

find arabic word in a string with Nunation

i want find a Arabic word with Nunation in a TextView and highlight this,
for example if my word is "اشهد" whitout Nunation i want to find word position in "وَ اَشْهَدُ اَنْ لا اِلهَ اِلاَّ اللَّهُ" with Nunation .
Hi Please see below class i created. It is so basic and did not bother about memory consumption. You guys can optimise yourself.
http://freshinfresh.com/sample/ABHArabicDiacritics.java
If you want to check without nunation(harakath) contains in an arabic String,
ABHArabicDiacritics objSearchd = new ABHArabicDiacritics();
objSearchdobjSearch.getDiacriticinsensitive("وَ اَشْهَدُ اَنْ لا اِلهَ اِلاَّ اللَّهُ").contains("اشهد");
If you want to return Highlighed or redColored searched portion in String.
Use below code
ABHArabicDiacritics objSearch = new ABHArabicDiacritics( وَ اَشْهَدُ اَنْ لا اِلهَ اِلاَّ اللَّهُ, اشهد);
SpannableString spoutput=objSearch.getSearchHighlightedSpan();
textView.setText(spoutput);
To see start and end position of search text,
Use below methods,
/** to serch Contains */
objSearch.isContain();//
objSearch.getSearchHighlightedSpan();
objSearch.getSearchTextStartPosition();
objSearch.getSearchTextEndPosition();
Please copy shared java class and enjoy.
I will spend more time for more feature if you guys request.
Thanks
search ولد in INPUT :
public void RegexMatches() {
String INPUT ="ى لَیْلَهِ تَمامِهِ وَکَمالِهِ فَما کانَتْ اِلاّ ساعَهً وَاِذا بِوَلَدِىَ الْحَسَنِ قَدْ" ;
Pattern p = Pattern.compile("و[\\u064B-\\u064F\\u0650-\\u0656]*ل[\\u064B-\\u064F\\u0650-\\u0656]*د");
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}

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.

HTML Formatted String inserting into TextViews and EditText

All,
I have a database that will store an HTML tagged text to retain formatting information from an EditText. I create this string using HTML.toHtml(EditText.getText). I notice this method wraps whatever Spanned Text is put in it with <p> and </p>. The issue with that is when I got to use the method HTML.fromHtml(HTMLFormattedString) and then use the setText method of either a TextView or EditText there are two extra lines at the end of my actual text, which makes sense because that is how the paragraph tag works with HTML.
My question is is there anyway to make the textView or EditText shrink to not display the extra blank lines? What is the simplest way to do this? I have experimented with just removing the last <p> and </p>, but that only works if the user did not enter 3 or more new lines with the return key.
I ended up searching for white space at the end of the spanned text that was created and removed it. This took care of extra spaces due to the <p> </p> and was less time consuming than overriding the mentioned class to achieve the same results.
public SpannableStringBuilder trimTrailingWhitespace(
SpannableStringBuilder spannableString) {
if (spannableString == null)
return new SpannableStringBuilder("");
int i = spannableString.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(spannableString.charAt(i))) {
}
return new SpannableStringBuilder(spannableString.subSequence(0, i + 1));
}
Well this is just a round about approach. I had the same issue. And you are provided with two options,
1)As you said that paragraph tag works the way what you have suspected. What it does , it appends two "\n" values to the end of each <\p> tag. So you can convert the html to string and remove the last two characters which are usually two "\n"s
or
2) You have get into the Html Class itself. That is, you have to override the HTML class and look for handleP(SpannableStringBuilder text) and change its core logic a little bit.
private static void handleP(SpannableStringBuilder text) {
int len = text.length();
if (len >= 1 && text.charAt(len - 1) == '\n') {
if (len >= 2 && text.charAt(len - 2) == '\n') {
return;
}
text.append("\n");
return;
}
if (len != 0) {
text.append("\n\n");
}
}
As you can see here, it appends two "\n" in len!=0 which is were you have to do the change.

Injecting non-English characters in Android

I am programming on a remote control app. One of the tasks is injecting characters. The code I am currently using looks like this:
Instrumentation instr = new Instrumentation();
String str="a";
// basically the same like calling instr.sendStringSync(str);
char[] chars = str.toCharArray();
KeyCharacterMap keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
KeyEvent[] keyEvents = keyCharacterMap.getEvents(chars);
if (keyEvents != null) {
for (KeyEvent kev : keyEvents) {
instr.sendKeySync(kev);
}
}
That works perfectly on English characters (The characters show up in EditText boxes). However, if I am trying to inject e.g. Korean characters, this fails. The function getEvents returns null, even when I have configured Korean language and keyboard.
I know there is another method for injecting strings directly:
KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(), str, 0, 0);
instr.sendKeySync(event);
This is not working either - no characters shown in EditText boxes, and onKeyMultiple() is not called either in my test activity.
This is strange since dispatchKeyEvent() with the same event works in my test activity:
KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(), str, 0, 0);
dispatchKeyEvent(event);
My remote control app needs to inject events no matter to which activity. This is possible using Instrumentation (with android.permission.INJECT_EVENTS and a signature with the platform key).
How can I inject non-English characters using instrumentation?
Is there another way to accomplish this? E.g. Using dispatchKeyEvent (has to work for other activities/apps as well).
I leave the part above as extra info. I have found a solution. It requires to have root, but if you can sign with the application key I guess that's not a problem. What you can do is edit the file Virtual.kcm (/system/usr/keychars/Virtual.kcm), which is the default key character map (kcm). You can add any character you want, and then use the method Instrumentation.sendStringSync(String string), because it will be able to generate KeyEvents from the new kcm.
I had some problems editting the kcm on the phone, so what I did was to copy it on a computer, edit it there and then copy it back to the device.
I hope this helps!
In this link, the following content appears. It seams that the virtual keyboard has a US keyCharacterMap and layout, no matter what you choose on settings. I haven't been able to find a way to solve this.
Language Note
Android does not currently support multilingual keyboards. Moreover, the built-in generic key character map assumes a US English keyboard layout.
OEMs are encouraged to provide custom key character maps for their keyboards if they are designed for other languages.
Future versions of Android may provide better support for multilingual keyboards or user-selectable keyboard layouts.
You can use this method and InputFilter for EditText:
private boolean isLatinSymbolOrDigit(char c)
{
// Allow [a-zA-Z0-9]
if ('0' <= c && c <= '9')
return true;
if ('a' <= c && c <= 'z')
return true;
if ('A' <= c && c <= 'Z')
return true;
return false;
}
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 (isLatinSymbolOrDigit(source.charAt(i)))
{
}
else
{
//wrong character
return "";
}
}
return null;
}
};
editText.setFilters(new InputFilter[] {filter});

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

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
}

Categories

Resources