Mask for EditText in Android - 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 });
}
}

Related

EditText allow only alphabets, digits of all languages

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 });

Space button click puts Auto suggestion to the EditText Android

Please, help me to solve this strange problem. I try to implement EditText, where user can add links to user profiles, hashtags and so on. I have OnTextChanged method where I get current text from EditText, process it and put it to EditText backward.
#OnTextChanged(R.id.share_article_say_something)
public void onTextChanged() {
if (mIsTextChangedManually) {
mIsTextChangedManually = false;
return;
}
mIsTextChangedManually = true;
SpannableStringBuilder builder = mCommentsSpannable.format(mSaySomethingTv.getText().toString());
mSaySomethingTv.setTextKeepState(builder);
}
EditText looks like that
<com.slangwho.views.SWEditText
android:id="#+id/share_article_say_something"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="left"
android:textColor="#color/black"
android:textColorHint="#color/my_friend_pressed_color"
android:background="#android:color/transparent"
android:textSize="#dimen/splash_screen_button_text_sp"
android:hint="#string/say_something"
android:layout_margin="10dp"
android:imeOptions="actionDone"
android:textCursorDrawable="#drawable/ed_cursor_drawable_black"
app:fontName="ProximaNova-Regular"/>
This EditText extends regular EditText just to add 1 additional parameter, which is fontName.
When I type some text I receive wrong suggestions(cursor is after single standing "s")
When I typing "Space", I receive:(The First suggestion adds after single standing "s")
It turned out that it was a problem with Samsung Swipe Keyboard. When I set text to the edit text using EditText.setText() or EditText.setTextKeepState() the keyboard suggestions behave strange. The solution was not to set text to the EditText, but set TextWatcher to the EditText and transform Editable in the method afterTextChanged(Editable s).
public class SocialTextWatcher implements TextWatcher {
CommentsSpannable mCommentSpannable;
public SocialTextWatcher(CommentsSpannable commentsSpannable) {
mCommentSpannable = commentsSpannable;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
mCommentSpannable.formatEditable(s);
}
}

Fixed-size multi-line EditText?

I have an EditText that I want to use so people can input a short bio.
So I am trying to make it so it's fixed at, for example, a box that is 4 lines high. I don't want it to "scale" or "shift" with the input -- I'm trying to make it a fixed box of a fixed number of lines with word-wrap.
I did try adding lines="4" and maxLines="4" and inputType="textCapSentences|textMultiLine" but it doesn't quite seem to be right. When I set text, it appears in the middle of the EditText (and not the upper left), and it seems to let me hit enter a whole lot so I can have a word in the first row and then a character like 20 rows down.
Current XML:
<EditText
android:background="#00ff00"
android:id="#+id/editTextId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="4"
android:maxLines="4"
android:inputType="textCapSentences|textMultiLine"
android:gravity="left|top"/>
I'm using a background of green so I can more easily see it for now. Right now this lets you type as much as you want, but I want to limit it to the space as given.
There is in no built code to achieve what you need. But here is a workaround -
private String enteredText;
edtText.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) {
}
#Override
public void afterTextChanged(Editable s) {
if (edtText.getLineCount() > 4) {
edtText.setText(enteredText);
edtText.setSelection(edtText.getText().length()); //This statement is to move the cursor at the end of the text otherwise it'll be moved to the start of the text.
}
else {
enteredText = edtText.getText().toString();
}
}
});
Hope this helps !!
to fix the centered text issue add:
android:gravity="top|left"
To prevent the user from inputting more then 4 lines, you'll need to do it by code.
Add a TextWatcher to the EditText, and check the number of lines after each text-change:
TextWatcher textWatcher = new TextWatcher() {
onTextChanged(CharSequence s, int start, int before, int count) {
// Check number of lines here
}
};
editText.addTextChangedListener(textWatcher);
Just add this attribute to your edittext
android:inputType="textMultiLine"

Android set edittext max limit in bytes

In android, I want an edit text with limit of 255 bytes, so when the user will try to exceed this limit, it won't let him to write.
All the filters I saw are using characters limit, even in the xml layout.
So how can I set a filter to the edittext in order to limit to 255 bytes?
One solution would be.
Use a TextWatcher on the EditText to get a String of the typed text.
Use myString.getBytes().length; to get the size of the string in bytes.
perform an action on the EditText based on a threshold you have set in bytes.
final int threshold = 255;
EditText editText = new EditText(getActivity());
editText.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) {
int i = s.toString().getBytes().length;
if(i < threshold){
//Action needed
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
You will need to apply this example to your own solution.
One Charterer (char) is of 2 bytes, if you set the android:maxlength="128" in your editText, you will get the limit you want
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:lines="1"
android:maxLength="128"
android:singleLine="true"
android:visibility="visible" />

How to force EditText to start text with capital letter?

I have an EditText and I need the text in it (when user types in) to be started with capital letter.
Be careful if you add both android:capitalize="sentences" and android:inputType="text", as the latter seems to have priority over the first and the input will not be capitalized.
There's a specific inputType for automatically capitalizing the first letter:
android:inputType="textCapSentences"
See http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
The options for android:capitalize are
android:inputType="none", which won't automatically capitalize anything.
android:inputType="sentences", Which will capitalize the first word of each sentence.
android:inputType="words", Which Will Capitalize The First Letter Of Every Word.
android:inputType="characters", WHICH WILL CAPITALIZE EVERY CHARACTER.
Apparently it has been changed to inputType instead of capitalize
Use
android:inputType="textPersonName|textCapWords"
as using only "textPersonName" is not enough so name's first letters would be capitalized.
Similarly with postal addresses:
android:inputType="textPostalAddress|textCapSentences"
Try this way,
testEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
or android:inputType="textCapSentences" will only work If your device keyboard Auto Capitalize Setting enabled.
Add this in your XML
android:inputType="textCapWords"
android:inputType="textCapSentences" will work for sentences. However, I needed to capitalize every word in a full name field.
In the layout xml, add android:inputType=textCapSentences
You used the word "Enforce". So try this. Just pass your edittext as argument.
public static void setCapitalizeTextWatcher(final EditText editText) {
final TextWatcher textWatcher = new TextWatcher() {
int mStart = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mStart = start + count;
}
#Override
public void afterTextChanged(Editable s) {
String input = s.toString();
String capitalizedText;
if (input.length() < 1)
capitalizedText = input;
else
capitalizedText = input.substring(0, 1).toUpperCase() + input.substring(1);
if (!capitalizedText.equals(editText.getText().toString())) {
editText.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) {
}
#Override
public void afterTextChanged(Editable s) {
editText.setSelection(mStart);
editText.removeTextChangedListener(this);
}
});
editText.setText(capitalizedText);
}
}
};
editText.addTextChangedListener(textWatcher);
}
In the layout xml, add android:capitalize="sentences"
In case of password which starts from upper case it will be:
android:inputType="textPassword|textCapSentences"
in case you ran into the annoying case of setting android:inputType=textCapSentences then ending up with one-liner EditText, here's the solution:
android:inputType="textCapSentences|textMultiLine"
Paste this in your edittext (xml):
android:capitalize="sentences"
edittext.setFilters(new InputFilter[] {new InputFilter.AllCaps()});
Adding input type in edit text as textCapSentences which will make first letter of the sentence capital
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="10dp"
android:gravity="center"
android:inputType="textCapSentences"
android:hint="Name"/>

Categories

Resources