EditText with only ascii letters. How? - android

Primary users of my app have 2 languages installed. English and other. Default system language is not English.
Users just use language switch button on software keyboard.
One specific EditText field in my app needs to accept only A-Z(capitalization issue is not a problem) and spaces and no other characters (no digits, no non-latin chars,etc).
I understood about solutions with InputFilters like How to create EditText accepts Alphabets only in android? or with TextWatcher-derived but thy only allow app to simple ignore incorrect text and I need to be able to make user not even able to see non-latin1 letters in first place on their on-screen keyboard (I'm aware that it is possible to use hardware keyboard, this is not issue at this time).
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
Doesn't help too (language change button is still visible in keyboard).
I need something like iPhone: Change Keyboard language programmatically but for Android.
Do I have any other option except adding fake keyboard to my app?
iOS have .keyboardType = .asciiCapable and it works in such situations

You can use input filter and assign it to Edit texts
Refer to example below
public class AlphabetInputFilter implements InputFilter {
Pattern mPattern;
public AlphabetInputFilter() {
mPattern = Pattern.compile("[a-z]");
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String formatedSource = dest.subSequence(0, dstart).toString();
String destPrefix = source.subSequence(start, end).toString();
String destSuffix = dest.subSequence(dend, dest.length()).toString();
CharSequence match = TextUtils.concat(formatedSource, destPrefix, destSuffix);
Matcher matcher = mPattern.matcher(match);
if (!matcher.matches())
return "";
return null;
}
}
And you can assign it edit text
mEdittext.setFilters(new InputFilter[]{
new AlphabetInputFilter()});
user will not be able to enter any value other than a to z

I found at least semi-working solution based on https://stackoverflow.com/a/49710730/1063214
imeOptions="flagForceAscii"
on EditText.
Now at least non-english keyboard is not shown (and digits,etc are filtered anyway).

Related

How to extract text smileys from a string in android

I am working on an android application in which I want to convert all keyboard types smileys into emoji icons.
I am already using this library https://github.com/ankushsachdeva/emojicon to show Emoticons in my app.
Now, I want to convert the smileys which users will type using keyboard into emoticons.
Ex: If user type the string Hello World :) :P:
1. Then I need to first extract these smiley symbols and for that I need a regex pattern which will extract all these types of symbols from a string.
2. I need to find Unicode of these symbols and then convert these symbols in emoticons using the above library.
Please help me, so that I can proceed here.
this lib is using ImageSpans and SpannableStringBuilder like here:
EmojiconTextView
public void setText(CharSequence text, BufferType type) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mTextStart, mTextLength);
super.setText(builder, type);
}
you can always remove spans from current SpannableStringBuilder and get plain text
if you want to set spans "in fly" just use TextWatcher for your EditText, smth like here: EmojiconEditText
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
EmojiconHandler.addEmojis(getContext(), getText(), mEmojiconSize);
}
this lib seems to do all work for you, just use Views from lib (Emojicon prefix) instead usual ones, e.g.
<ankushsachdeva.emojicon.EmojiconTextView
android:id="#+id/emojicon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
emojicon:emojiconSize="24dip"
android:gravity="center"/>
instead EditText in XML layout files

Android EditText, show both comma and dot as possible separator in case of numberDecimal input type

I need to let user choose between two variants when he inputs decimal number:
use comma(,) as separator
use dot(.) as separator
By default if I use inputType="numberDecimal" in the EditText xml config - EditText shows only digits and comma (,) as possible separator.
I've tried to use android:digits="0123456789, in my EditText config, but without result - EditText widget shows just digits and comma.
I want to have both variants (. and ,) available for user on on-screen keyboard when he tries to input decimal number.
Could you please advise?
Specifying both android:inputType="numberDecimal" and android:digits="0123456789,." will display a keyboard with mostly just numbers and punctuation (depending on the user's chosen keyboard). It will also limit the characters accepted as input to those in your digits attribute.
If you'd like to further limit the keyboard to display only certain characters, you'll need to define a custom one. Here's one of the better tutorials on doing that.
Use proper validation. Let the user see full keyboard but he remain aloof of using it. Means user should not be able to use or input anything using keyboard.
etlocation = (EditText) findViewById(R.id.etlocation);
and used this
etlocation.getText().toString();
if (!isValidLocation(etlocation.getText().toString().trim()))
{
etlocation.setError("Invalid location");
}
validate this
public static boolean isValidLocation(String str) {
boolean isValid = false;
String expression = "^[0-9,.]*$";
CharSequence inputStr = str;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
You can read this link and also read allow only number and period(.) in edit text in android. Hopefully are helpful from those links. Best of Luck!
You can create a custom keyboard.
The below link shows a nice example of custom keyboard
http://www.mediafire.com/download/39q7of884goa818/myKeyborad2.zip
and check this link also
How to develop a soft keyboard for Android?

Android: Deleting characters in EditText with TextWatcher still shows characters in suggestions

In my activity I have an EditText to capture a file name. I am using a TextWatcher to prevent users from entering certain characters that I don't want them to use in their filename. Essentially I only want users to enter in the following characters: [a-zA-Z_0-9].
#Override
public void afterTextChanged(Editable text) {
String textStr = text.toString();
int length = text.length();
if (!Pattern.matches("\\w*", textStr)) {
text.delete(length-1, length);
}
}
EDIT: Adding more code
in onCreate(...)
fileNameEditText = (EditText)findViewById(R.id.UploadPhoto_fileNameEditText);
fileNameEditText.addTextChangedListener(this);
in layout xml file
<EditText
android:id="#+id/UploadPhoto.fileNameEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20sp"
android:layout_marginRight="10sp"
android:layout_toRightOf="#id/UploadPhoto.fileNameLabel"/>
This works perfectly by preventing users from entering in things like "\" and ".". The problem that I'm having is that if they type these characters they show up in the word suggestions box. Its kind of annoying because if you try to delete a character using backspace, it deletes from the suggestion first (even though the character doesn't show up in EditText box).
How do you prevent the unwanted characters from showing up in the word suggestiong box?
See screen shot below. Notice that the "-" (hyphen) appears in the suggestion box, but not in the EditText. Also notice that there is another valid character in the suggestion box after the hyphen that also does not show up in the EditText. This essentially blocks the user from entering in more text until they delete the hyphen, even though its not in the EditText.
UPDATE: The same issue arises and can be reproduced by using an InputFilter instead of a TextWatcher.
UPDATE: I'd like to clarify that my goal is not to suppress the Suggestions altogether. The issue is that when you prevent specific characters from appearing in the EditText, they still show up in the Suggestions. My goal (which the bounty is for) is to prevent the same specific characters from appearing in the Suggestions.
You should use an InputFilter to restrict some characters in Edittext
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});
It seems that the emulator doesn't support the textNoSuggestions, and the corresponding FLAG (TYPE_TEXT_FLAG_NO_SUGGESTIONS). It's realy anoying, but hey: you're not developing for emulator users, you shouldn't be preoccupied with this, it'll work fine on allmost all devices.
(Note that this flag is available only from API level 5)
We can do that in the layout xml file and achive what you have asked in an easy way, insert the line
android:numeric="your custom elements"
android:digits="your custom elments"
android:inputType="your custom elements"
when you implement these then you will be able to type the words that you want to.

Permit only 1 character in EditText and always overwrite when user input it

I need to make an EditText which would accept only one character and only character (letter/alpha). And if user enters other char, it should replace existing one (like overwrite method of text input with 1 allowed symbol).
I know how to set the max length of text in properties. But if I set it
to 1, then no other char could be inserted before user deletes an
existing one. But I want to replace existing char with that new entered
one automatically without manual deleting. How to do that?
I know how to set property to allow only digits in an EditText, but I
can't figure out how to allow only chars. So the second question is how to allow only characters in EditText?
Currently I'm using an EditText with max text size=2 with the following code:
final EditText editLetter = (EditText)findViewById(R.id.editHouseLetter);
editLetter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (s!=null && s.length()>1){
editLetter.setText(s.subSequence(1, s.length()));
editLetter.setSelection(1);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
The point is, when a user enters a second char, the first one should be deleted. Making text size to 2 allows user to enter another char after one has been already entered.
I don't really understand how it works but it does :). And additionally I had to point cursor in EditText to the last position because it always goes to beginning which makes unable to enter anything at all. Didn't get why is that either.
Main point of this solution is that it has a 2-chars sized EditText, but I want it 1-char sized. And it allows to enter anything besides the letters(chars/alpha) and I want nothing but chars.
Using the advice provided by sgarman and Character.isLetter() function, afterTextChanged method looks this way now:
public void afterTextChanged(Editable s) {
int iLen=s.length();
if (iLen>0 && !Character.isLetter((s.charAt(iLen-1)))){
s.delete(iLen-1, iLen);
return;
}
if (iLen>1){
s.delete(0, 1);
}
}
I've discovered that using Selection.setSelection is not required in this case. Now it has a filter allowing input of letters only. It's almost the answer that I want. The only one thing left is how to do the same with 1-symbol sized EditText?
Add the following line to your layout XML file android:maxLength="1"
Following is an example of adding it to an editText element:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLength="1" >
I faced the same problem and found this more straightforward solution. Please refer to this blog for more details.
Edit: Please note that my answer is for defining the max number of characters, however, it does not overwrite upon user input.
Try:
s.delete(0, 1);
Selection.setSelection(s, s.length());
I wanted to do the same thing and I used your code in afterTextChanged(Editable s) and also set one filter on the editText like this.
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(2)});
It worked as we wanted.

Android: are there any good solutions how to validate Editboxes

For example, I want to Validate Minimum-Length, and if it's Email, a PhoneNumber.
How is this possible in android. I want to validate.
If you wan to prevent user to type something, then extend the InputFilter and register it with your EditText.
// built in InputFilter.LengthFilter limits the umber of chars
EditText.setFilters(new Filter[]{new InputFilter.LengthFilter(100)})
There are a number of things that you can do to validate
Add input filters. More on it is here http://developer.android.com/reference/android/text/InputFilter.html How to add filter to editable view is mentioned here http://developer.android.com/reference/android/text/Editable.html#setFilters%28android.text.InputFilter
Use TextWatchers to modify the content on the go. More on TextWatchers is here http://developer.android.com/reference/android/text/TextWatcher.html Set this up for your EditText using http://developer.android.com/reference/android/widget/TextView.html#addTextChangedListener(android.text.TextWatcher)
Note: There are few of them implemented in Android itself. Make use of them if you can. Look for subclasses in the documentation for TextWatcher and InputFilter
For the validation of Text box
1. minimum length: u can directly give the length of that text.
2. mail validation:
public boolean isEmailValid(String email)
{
String regExpn =
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
CharSequence inputStr = email;
pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(inputStr);
if(matcher.matches())
return true;
else
return false;
}
1. For phone number: If you want to fix length then give the length and the input type is number.
Also take a look here :) Android: Validate an email address (and more) in EditText

Categories

Resources