EditText allow only alphabets, digits of all languages - android

I have an EditText in which i want to allow only alphabets and numbers of any language. I tried with different android:inputType and android:digits in XML.
I tried with set TextWatcher to edittext in which onTextChanged() is like
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
switch (et.getId()) {
case R.id.edtMultiLang: {
et.removeTextChangedListener(watcher2);
et.setText(s.toString().replaceAll("[^[:alpha:]0-9 ]", ""));
// et.setText(s.toString().replaceAll("[^A-Za-z0-9 ]", ""));
et.addTextChangedListener(watcher2);
break;
}
}
}
This is working fine. But whenever i tried to clear text, cursor is moving to start for every letter. Means when i clear a single letter, cursor moving to start.
If i use like android:digits="abcdefghijklmnopqrstuvwxyz1234567890 ", it allows me to type only alphabets and numbers of english. It is not allowing me to enter any other language text As i given only English related alphabets here. But my requirement is to allow copy/paste of other language's alphabets and letters also.
I hope we can do this by using Patterns, TextWatcher and InputFilter. But i didn't find better way.
Please let me know if there any way to do this.

The option you mention to resolve the problem is easy and fast, if you use a filter your code will be like this:
public static InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String blockCharacterSet = "~#^|$%*!#/()-'\":;,?{}=!$^';,?×÷<>{}€£¥₩%~`¤♡♥_|《》¡¿°•○●□■◇◆♧♣▲▼▶◀↑↓←→☆★▪:-);-):-D:-(:'(:O 1234567890";
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
return null;
}
};
editText.setFilters(new InputFilter[] { filter });

Related

Open the keyboard as numeric without adding InputType.TYPE_CLASS_NUMBER

Have been trying to implement a way for the soft keyboard to open first the Numeric key without saying that the EditText is numeric.
Is this possible ? if yes how ?
The editText btw are added dynamic, so can't do changes on XML files
You can set input type programmatically.
EditText editText=new EditText(this);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
Edit
You can use InputFilters
public class NumericInputFilter implements InputFilter {
String regEx = new String("^[0-9]+$")
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
int dend) {
if (source != null && !source.toString().matches(regEx) && !source.toString().equals( "")) {
return "";
}
return source;
}
and on your editText, editText.setFilters(new InputFilter[]{new NumericInputFilter()});
If we set the editText such as editTextField.setRawInputType(Configuration.KEYBOARD_QWERTY);
it will open a keyboard with numeric first and let me choose the normal one and input letters also.

Android EditText, detecting characters before user selection when inputing Chinese

Can i detect characters the user is typing before user's touch selection on the Chinese word?
iOS can achieve this.
This is Android, the EditText TextWatcher will get nothing before user selection.
Read the official doc here.
By using a TextWatcher, you'll have access to the afterTextChanged(), beforeTextChanged() and onTextChanged() methods. Now you can see what pinyin the user enters as he enters it and then change your hanzi suggestions as his input changes.
Try this way
InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
//source : latest character typed in edittext
//dest : all characters except source
// HERE YOU WILL GET CALLBACK EVERY TIME key ENTERED IN EDITTEXT
return null;
}
};
edtText.setFilters(new InputFilter[]{filter});

Override the default behavior of Backspace in AutoCompleteTextView

I'm using a AutoCompleteTextView, the default behavior of the backspace button goes something like this.
Say i type "Ar", this gives me a suggestion "Argentina", i select "Argentina" from the drop down...The Text now becomes "Argentina ". But say i need to remove the last character, so I hit backspace on the keyboard, the AutcompleteTextView removes all the text till the point i typed (ie. the text now becomes "Ar" again).
How do i eliminate this behavior and let the text in the AutoComplete to behave normally?
At first I thought it was some kind of SpannableString so i called "clearSpans()" but it doesn't seem to work. Any pointers?
Thanks in advance. :)
I think you use the MultiAutoCompleteTextView which add the setTokenizer(new SpaceTokenizer()).
If you use
AutoCompleteTextView instead of MultiAutoCompleteTextView and remove the setTokenizer(...)
the problem will be gone.
I did not find any solution, but finally I figured out, this code worked for me:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
// removing QwertyKeyListener.Replaced span
Editable text = editText.getText();
Object[] spans = text.getSpans(0, text.length(), Object.class);
if (spans != null) {
for (int i = spans.length - 1; i >= 0; i--) {
Object o = spans[i];
String desc = "" + o; // This is a hack, not a perfect solution, but works. "QwertyKeyListener.Replaced" is a private type
if (desc.indexOf("QwertyKeyListener$Replaced") != -1) {
text.removeSpan(o);
}
}
}
} catch (Throwable e) {
MyUtil.msgError(e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});

Permanent hint in EditText

I have a situation where I would like the user to complete a sentence for me. For example, consider a EditText with a hint of "The last time I ". Normally, when a user clicks an EditText, the hint disappears, but I would like it to stay. Additionally, I would like the text to be permanent, so that it cannot be erased... leaving the user with only one option... complete the sentence.
The first part is fairly simple, just use the setText() method of EditText to place the hint. The difficult part is the latter. How can I have text in an EditText that the user cannot erase?
Well couldn't you do it in code? Some algorithim like, if the text is less than 16 characters (length of "The last time I ") then set the text to that. Therefore whenever they clicked it, if they tried to erase it, it would just go back to the default text.
Also, another idea..why don't you just make a TextView thats right edge aligns with the left edge of the EditText box, the user would never know that it was another box. This is acutally the best solution, if you don't want the text ever to be edited, just make it a TextView
Described problem can be solved using android.text.TextWatcher.
public class CompleteSentenceWathcher implements TextWatcher {
private final String initialText;
private int start;
private int after;
private int count;
public CompleteSentenceWathcher(String initialText) {
this.initialText = initialText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
this.start = start;
this.count = count;
this.after = after;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(start < initialText.length()) {
if(s.toString().startsWith(initialText)) {
return;
}
if(count >= 1 && after == 0) {
if(start+count+1 <= initialText.length()) {
s.replace(start, start+count, initialText.substring(start, start+count+1));
} else {
s.replace(start, start, initialText.substring(start, start+1));
}
} else if(count == 0 && after >= 1) {
s.delete(start, start+after);
}
}
}
}
Create an instance of EditText and add the TextWatcher.
EditText editText = new EditText(this);
editText.setText("I love");
editText.addTextChangedListener(new CompleteSentenceWathcher(editText.getText().toString()));
I've implemented this with an InputFilter, where _PERMANENT_HINT_TEXT is the text at the end of the EditText that I don't want the user to be able to modify. I recommend adding a color span to it, so that it is grayed out to hopefully look like a hint/disabled section of text. This should hopefully improve the UX as they should automatically assume it is unmodifiable, and not just wonder why some part of the EditText (that they usually can completely change) isn't "working". This approach allowed the text to be set after
the InputFilter was set on the EditText, which was a requirement for me since I used this on an EditTextPreference.
To be clear, I needed the permanent text to exist at the end of the EditText, instead of the beginning, but that should be symmetrical to my implementation.
new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int source_start, int source_end,
Spanned destination, int destination_start, int destination_end) {
final int protected_text_start = (TextUtils.isEmpty(destination)? source.length() : destination.length()) - _PERMANENT_HINT_TEXT.length();
// Allows input into unprotected region
if (source_start + destination_start - source_end < protected_text_start)
return null;
// Prevents deletion of protected region
else if (TextUtils.isEmpty(source))
return destination.subSequence(destination_start, destination_end);
// Ignores insertion into protected region
else
return "";
}
}
use EditText.setFilters(new InputFilters[] { /* InputFilter goes here */ }; to add it to the desired EditText.
Just checking for the length wouldn't be adequate... I could type "This is a really long text I put into the box" and it would accept it even though it doesn't begin with "The last time I" string.
Personally, I would probably go for the prevention method suggested of using a TextView over that of a check on the way out. But if you're going to validate it afterwards, you'd actually need to check the beginning of the returned string.

Mask for EditText in Android

I want to limit input in the EditText of all symbols except figures, "?" And "*". How I am able to do it?
If you also have a maximum strict length of your string, you can use a mask. I'm not sure that it's the right solution, but it's the easiest one. An easy way use a mask in your Android programs in Android Studio is to use MaskedEditText library (GitHub link).
I can not understand what does mean: figures, "?" And "", so I suppose just "?" and "". So the code is:
In your build.gradle:
compile 'ru.egslava:MaskedEditText:1.0.5'
And in your layout:
<br.com.sapereaude.maskedEditText.MaskedEditText
android:id="#+id/phone_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:typeface="monospace"
mask:allowed_chars="?*"
mask:mask="##########"
app:keep_hint="true"
/>
This code creates an EditText that can contain ONLY "?" and "*" and max length is 10. Feel free to ask your questions :-)
You could add a TextWatch via addTextChangedListener. afterTextChanged allows you to modify the text after it was modified.
(Keep in mind that there are many ways to modify a text field - entering text, auto-complete through IME, copy and paste). Handle those properly in the TextWatch.
By this, we can restrict the user to not type ? and *
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/register_text_size"
android:layout_weight="1"
android:id="#+id/first_name"
android:padding="14dp"
android:digits="##$%^&()_-+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12"
android:singleLine="true"
android:hint="#string/first_name"/>
you can check your input from edittext.addTextChangeListener method.
etAdjustmentInput.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//checking the length of input
if (etAdjustmentInput.getText().toString().trim().length()<=0){
// if length less then or equals 0 show warning or make button not clickable
tvAdjustmentInfoOk.setClickable(false);
tvAdjustmentInfoOk.setTextColor(getResources().getColor(R.color.time_color));
}
else {
// input length greater then 0 now check the input type according to your requirement
tvAdjustmentInfoOk.setClickable(true);
tvAdjustmentInfoOk.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
if(s.equals("?")){
//do your task
}
else{ // whatever you want to tell the user
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Inside onTextChanged method you can restrict the user to maximum length and also you can check the input type according to your requirement
Try this
From this code you can enter 0 to 9 digits and only two special character ? and *.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/first_name"
android:digits="?*1234567890"
android:singleLine="true"
/>
public class MainActivity extends Activity {
private EditText editText;
private String blockCharacterSet = "?*";
private InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && !blockCharacterSet.contains(("" + source))) {
return "";
}
return null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText.setFilters(new InputFilter[] { filter });
}
}

Categories

Resources