Prevent user to add text after 10 commas entered in edittext - java

I have to create a comma-separated array. So after 10 comma edittext should not accept the text or latter enter by user <- I have to do this. Here's the code I am using. but it goes to infinite loop after if condition in onTextChanged().
addTagsEt.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) {
if (tagsArray != null && tagsArray.length == 10) {
Toast.makeText(CreateJobTwoActivity.this, "Only 10 tags considered", Toast.LENGTH_SHORT).show();
addTagsEt.setText(addTagsEt.getText().toString().substring(0, addTagsEt.getText().toString().length() - 1));
}
}
#Override
public void afterTextChanged(Editable s) {
if (addTagsEt.getText().toString().contains(",")) {
tagsArray = addTagsEt.getText().toString().split("\\s*,\\s*");
tagsArr.addAll(Arrays.asList(tagsArray));
}
}
});

Change onTextChanged function to:
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
String str = s.toString();
int l = str.length() - str.replaceAll(",","").length();
if (l >= 10){
Toast.makeText(CreateJobTwoActivity.this, "Only 10 tags considered", Toast.LENGTH_SHORT).show();
String t = str.substring(0,start) + str.substring(start+count);
addTagsEt.setText(t);
addTagsEt.setSelection(start,start);
}
}
}

Related

How to get the last word typed in a `EditText`?

I am building a proto social network and I give the possibility to my users to Tag another user with the # , I'm using an autocomplete textview to show the dialog with the users # searched but I need to know when a user typed "#" and the letters following in the editext . I found this answer and it's exaclty what I need BUT I dont want to only get one character. I want the whole word to make a search in my database . Example, user types "#Jordan" in the middle of his paste text . I need to get the "#" and the "#Jordan " . How can I do it ?
Here s an example of my code
private final TextWatcher textWatcher = 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) {
if (!TextUtils.isEmpty(s) && start < s.length()) {
if (!mentionAdapter.isEmpty()) {
mentionAdapter.clear();
}
String lastWord = s.toString().substring(s.toString().lastIndexOf(" ") + 1);
if (lastWord != null){
if (lastWord.length() != 0) {
switch (lastWord.charAt(0)) {
case '#':
if (getAdapter() != hashtagAdapter) {
setAdapter(hashtagAdapter);
}
break;
case '#':
if (getAdapter() != mentionAdapter) {
setAdapter(mentionAdapter);
}
break;
}
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I am aiming you are working on android java so here is the answer to your question
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String capturedString = getText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
this function will work whenever you tab spacebar "#Jordan " you will get string after '#' and before ' ' means you will get "Jordan" as a string
public String getText(String s) {
String startChar = "#";
String endChar = " ";
String output = getStringBetweenTwoChars(s, startChar, endChar);
System.out.println(output);
}
here is getStringBetweenTwoChars function
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
You can do that by following code, If you want to #java from the string
**Hello this is #java the best programming language **
edt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
String str = editable.toString();
String seperator = "#";
int seoPos = str.indexOf(seperator);
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(str);
boolean found = matcher.find();
if (seoPos != -1 && !found){
Log.d("TextChanged0","current Char "+str.substring(seoPos-1+seperator.length()));
}
}
});
String last = s.toString().substring(s.toString().lastIndexOf(" ") + 1);

Uppercase specific words in EditText

Inside EditText I want to know how to capitalize on specific words. The code is below.
editText.addTextChangedListener(new TextWatcher() {
private static final String KEYWORD = "rain";
private static final String KEYWORD1 = "music";
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
onSaveNote();
}
#Override
public void afterTextChanged(Editable s) {
onSaveNote();
try {
for (StyleSpan span : s.getSpans(0, s.length(), StyleSpan.class)) {
s.removeSpan(span);
}
// Add new spans for every occurrence of the keyword.
int i = 0;
while (i != -1) {
i = editText.getText().toString().indexOf(KEYWORD, i);
if (i != -1) {
s.setSpan(new InputFilter[]{new InputFilter.AllCaps()}, i, i + KEYWORD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
I tried searching for this but not found any. InputFilter doesn't work. How to do this?
If you know value of your text and start and end index of your text.
editText.getText().toString().substring(startIndex, endIndex).toUpperCase();
You can find start index in text like this:
editText.getText().toString().indexOf(KEYWORD)
and end index like this:
editText.getText().toString().indexOf(KEYWORD) + KEYWORD.length()
In afterTextChanged(), do the following:
#Override
public void afterTextChanged(Editable s) {
onSaveNote();
String[] words = s.toString().split("\\s+");
String output = "";
for (String word : words) {
if (word.equalsIgnoreCase(KEYWORD) || word.equalsIgnoreCase(KEYWORD1)) {
output += word.toUpperCase(Locale.getDefault()) + " ";
} else {
output += word + " ";
}
}
editText.setText(output.trim());
}

Changing TextInputLayout's Hint value as the user types in it

Here is my TextInputEditText inside TextInputLayout. The hint you can see is set on TextInputLayout.
The user must write 255 characters otherwise the post is not valid.
I want the digit 255 to decrease as the user types and when reached to 0, the hint should be blank.
Here is my code :
private int charactersLeft = 256; is declared outside onCreate method.
And this code is inside onCreate method :
final TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);
final TextInputEditText postTextInput = findViewById(R.id.post_text_input);
postTextInput.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) {
if (charactersLeft == 0) {
postTextInputBase.setHint(null);
} else {
postTextInputBase.setHint((charactersLeft - 1) + " characters left");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
I also tried to set charactersLeft to characterLeft -= 1 but, the java won't allow me to do that.
Then, how do I do this ?
Use app:counterEnabled="true"
Whether the character counter functionality is enabled or not in this layout.
Also use app:counterMaxLength="250"
Sets the max length to display at the character counter.
Try this
<android.support.design.widget.TextInputLayout
android:id="#+id/post_text_input_base"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:counterMaxLength="250">
<EditText
android:id="#+id/post_text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="UserName" />
</android.support.design.widget.TextInputLayout>
OUTPUT
EDIT
public class RecyclerViewActivity extends AppCompatActivity {
TextInputLayout postTextInputBase;
EditText postTextInputEditText;
int textLength = 9;
int len = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
postTextInputBase = findViewById(R.id.post_text_input_base);
postTextInputEditText = findViewById(R.id.post_text_input);
postTextInputBase.setHint(textLength + " characters left");
postTextInputEditText.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) {
// first check your EditText is empty or not
if (!TextUtils.isEmpty(postTextInputEditText.getText().toString())) {
int len = postTextInputEditText.getText().toString().length();
// than check that editText text length is less than max length or not
// for test case i have set max length 10
if (len < 9) {
// if length of text is less than max length than use minus one from max length and set error in your text input layout
textLength--;
} else {
textLength++;
}
postTextInputBase.setHint(textLength + " characters left");
} else {
textLength = 9;
}
}
#Override
public void afterTextChanged(Editable s) {
if(postTextInputEditText.getText().toString().isEmpty()){
textLength = 9;
postTextInputBase.setHint(textLength + " characters left");
}
}
});
}
}
OUTPUT
EDIT 2 If you need set hint than use this
postTextInputBase.setHint(textLength + " characters left");
OUTPUT
NOTE Don't forgot to set android:maxLength="10" in edittext
Try this. Works with your existing code.
int charactersLeft = 256;
final TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);
final TextInputEditText postTextInput = findViewById(R.id.post_text_input);
postTextInput.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 (s.length() == 0) {
postTextInputBase.setHint(null);
}else {
postTextInputBase.setHint((charactersLeft - s.length()) + " characters left");
}
}
});
and Add android:maxLength="256" to your TextInputEditText
You may do it programatically using setOnKeyListener on the edit text.
TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);
TextInputEditText postTextInput = findViewById(R.id.post_text_input);
postTextInput.setOnKeyListener((v, keyCode, event) -> {
// Do other things needed
postTextInputBase.setHint("Characters left: " + (256 - postTextInput.getText().length()));
return false;
});
To change Hint text only you can just change it on focus change.
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
editText.setHint("Enter name");
else
editText.setHint("Name");
}
});

EditText with phone number that has a dash [duplicate]

Instead of 5118710, it should be 511-8710. I'd like to add a dash after the user the user inputted 3 digits already in the EditText. The maximum length of the EditText is 7 digits only.
After I figured out the above problem, I've got stuck in coding again. When I already inputted 3 digits, it appends dash (that's what I'd like to happen) but my problem here is that the next 3 digits also appends dash (Like this: 511-871-)... Please help me with this. thanks!
txt_HomeNo.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean flag = true;
String eachBlock[] = txt_HomeNo.getText().toString().split("-");
for (int i = 0; i < eachBlock.length; i++) {
if (eachBlock[i].length() > 3) {
flag = false;
}
}
if (flag) {
txt_HomeNo.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDel = 1;
return false;
}
});
if (keyDel == 0) {
if (((txt_HomeNo.getText().length() + 1) % 4) == 0) {
if (txt_HomeNo.getText().toString().split("-").length <= 3) {
txt_HomeNo.setText(txt_HomeNo.getText() + "-");
txt_HomeNo.setSelection(txt_HomeNo.getText().length());
}
}
a = txt_HomeNo.getText().toString();
} else {
a = txt_HomeNo.getText().toString();
keyDel = 0;
}
} else {
txt_HomeNo.setText(a);
}
}
The most straightforward solution is to use PhoneNumberFormattingTextWatcher which will format the number according to the system locale.
XML:
<EditText
android:id="#+id/phone_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/enter_phone_number"
android:inputType="phone" />
Add addTextChangedListener() in your class:
EditText phoneNumber = (EditText)findViewById(R.id.phone_number);
phoneNumber.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
Implement the following modified addTextChangedListener for txt_HomeNo. The code below is checking if the length of the text entered is 3 and if it is then add the - to it. Not a very robust solution but it works!
txt_HomeNo.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
txt_HomeNo.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDel = 1;
return false;
}
});
if (keyDel == 0) {
int len = txt_HomeNo.getText().length();
if(len == 3) {
txt_HomeNo.setText(txt_HomeNo.getText() + "-");
txt_HomeNo.setSelection(txt_HomeNo.getText().length());
}
} else {
keyDel = 0;
}
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
I have a few small changes to the solution of neo108 so it can work with both soft keyboard and hard keyboard, in my code for example the edittext will follow the rule to automatically add " " at position 5 and 9.
txtPhone.addTextChangedListener(new TextWatcher() {
int keyDel;
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
txtPhone.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
keyDel = 1;
}
return false;
}
});
String currentString = txtPhone.getText().toString();
int currentLength = txtPhone.getText().length();
if (currentLength == 5 || currentLength == 9) {
keyDel = 1;
}
if (keyDel == 0) {
if (currentLength == 4 || currentLength == 8) {
txtPhone.setText(txtPhone.getText() + " ");
txtPhone.setSelection(txtPhone.getText().length());
}
} else {
if (currentLength != 5 && currentLength != 9) {
keyDel = 0;
} else if ((currentLength == 5 || currentLength == 9)
&& !" ".equals(currentString.substring(currentLength - 1, currentLength))) {
txtPhone.setText(currentString.substring(0, currentLength - 1) + " "
+ currentString.substring(currentLength - 1, currentLength));
txtPhone.setSelection(txtPhone.getText().length());
}
}
}
I implemented a custom TextWatcher; this handles 10 and 11 digit phone numbers (i.e. 1-555-867-5309 and 555-867-5309). Allows adds, deletions, inserts, mass removal while maintaining proper cursor position.
public class CustomPhoneTextWatcher implements TextWatcher {
private final EditText editText;
private String previousString;
public CustomPhoneTextWatcher(EditText editText) {
this.editText = editText;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
// if the previous editable ends with a dash and new is shorter than previous
// additionally remove preceding character
if (previousString != null && previousString.endsWith("-") && editable.toString().length() < previousString.length()) {
previousString = editable.toString();
String removedCharacterPriorToDash = editable.toString().substring(0, editable.length() - 1);
editText.setText(removedCharacterPriorToDash);
int position = editText.length();
Editable etext = editText.getText();
Selection.setSelection(etext, position);
} else {
previousString = editable.toString();
String numericString = StringUtils.removeNonnumeric(editable.toString());
int stringLength = numericString.length();
boolean startsWithOne = numericString.startsWith("1");
numericString = numericString.substring(0, Math.min(stringLength, 10 + (startsWithOne ? 1 : 0)));
int lastHyphenIndex = 6 + (startsWithOne ? 1 : 0);
int secondToLastHyphenIndex = 3 + (startsWithOne ? 1 : 0);
if (stringLength >= lastHyphenIndex) {
numericString = numericString.substring(0, lastHyphenIndex) + "-" + numericString.substring(lastHyphenIndex, numericString.length());
}
if (stringLength >= secondToLastHyphenIndex) {
numericString = numericString.substring(0, secondToLastHyphenIndex) + "-" + numericString.substring(secondToLastHyphenIndex, numericString.length());
}
if (numericString.startsWith("1")) {
numericString = numericString.substring(0, 1) + "-" + numericString.substring(1, numericString.length());
}
if (!numericString.equals(editable.toString())) {
editText.setText(numericString);
int position = editText.length();
Editable etext = editText.getText();
Selection.setSelection(etext, position);
}
}
}
}
StringUtils.removeNonnumeric(editable.toString()) is a call to this method:
public static String removeNonnumeric(String text) {
return text.replaceAll("[^\\d]", "");
}
Thanks for the all above answer.
The editText.setOnKeyListener() will never invoke when your device has only soft keyboard.
If we strictly follow the rule to add "-", then this code not always show desire result.
editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
but above code is best solution for formatting phone no.
Apart from above this solution, I write a code which work on all types of condition::
phoneNumber.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 (len > phoneNumber.getText().length() ){
len--;
return;
}
len = phoneNumber.getText().length();
if (len == 4 || len== 8) {
String number = phoneNumber.getText().toString();
String dash = number.charAt(number.length() - 1) == '-' ? "" : "-";
number = number.substring(0, (len - 1)) + dash + number.substring((len - 1), number.length());
phoneNumber.setText(number);
phoneNumber.setSelection(number.length());
}
}
});
this line of code required to add "-" on 3rd & 6th position of number.
if (len == 4 || len== 8)
Do it yourself by using OnEditTextChangedListener and insert dash by counting number of chars, Counting Chars in EditText Changed Listener
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
/**
* Auto-formats a number using -.
* Ex. 303-333-3333
* Ex. 1-303-333-3333
* Doesn't allow deletion of just -
*/
public class PhoneNumberFormattingTextWatcher implements TextWatcher {
private static final String TAG = "PhoneNumberTextWatcher";
private final EditText editText;
private String previousNumber;
/**
* Indicates the change was caused by ourselves.
*/
private boolean mSelfChange = false;
public PhoneNumberFormattingTextWatcher(EditText editText) {
this.editText = editText;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
// if the previous editable ends with a dash and new is shorter than previous
// additionally remove preceding character
Log.i(TAG, "Previous String: " + previousNumber);
//if self change ignore
if (mSelfChange) {
Log.i(TAG, "Ignoring self change");
mSelfChange = false;
return;
}
String phoneNumber = removeNonnumeric(editable.toString());
int stringLength = phoneNumber.length();
//empty case
if(stringLength == 0) {
mSelfChange = true;
editText.setText("");
return;
}
boolean startsWithOne = phoneNumber.charAt(0) == '1';
int maxLength = 10 + (startsWithOne ? 1 : 0);
//too large
if(stringLength > maxLength) {
Log.i(TAG, "String length is greater than max allowed, using previous string: " + previousNumber);
mSelfChange = true;
editText.setText(previousNumber);
Editable etext = editText.getText();
Selection.setSelection(etext, previousNumber.length());
return;
}
phoneNumber = formatPhoneNumber(phoneNumber);
if(previousNumber != null && phoneNumber.length() == previousNumber.length()) {
//user deleting last character, and it is a -
if(phoneNumber.endsWith("-")) {
phoneNumber = phoneNumber.substring(0, phoneNumber.length()-2);
}
}
mSelfChange = true;
previousNumber = phoneNumber;
editText.setText(phoneNumber);
Editable etext = editText.getText();
Selection.setSelection(etext, phoneNumber.length());
}
private String formatPhoneNumber(String phoneNumber) {
int stringLength = phoneNumber.length();
//check if starts with 1, if it does, dash index is increased by 1
boolean startsWithOne = phoneNumber.charAt(0) == '1';
//if the length of the string is 6, add another dash
int lastHyphenIndex = 6 + (startsWithOne ? 1 : 0);
if (stringLength >= lastHyphenIndex) {
phoneNumber = phoneNumber.substring(0, lastHyphenIndex) + "-" + phoneNumber.substring(lastHyphenIndex, phoneNumber.length());
}
//if the length of the string is 3, add a dash
int secondToLastHyphenIndex = 3 + (startsWithOne ? 1 : 0);
if (stringLength >= secondToLastHyphenIndex) {
phoneNumber = phoneNumber.substring(0, secondToLastHyphenIndex) + "-" + phoneNumber.substring(secondToLastHyphenIndex, phoneNumber.length());
}
//If the number starts with 1, add a dash after 1
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(0, 1) + "-" + phoneNumber.substring(1, phoneNumber.length());
}
return phoneNumber;
}
private static String removeNonnumeric(String text) {
return text.replaceAll("[^\\d]", "");
}
}

Android Edit text Masking

I want to add masking ..
like 00000-0000000-0
etusercnic.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) {
try {
String str = s.toString();
if (s.length() == 5 || s.length() == 13) {
str += "-";
etusercnic.setText(str);
etusercnic.setSelection(str.length());
}
} catch (Exception ignored) {
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
It works perfectly,when first time i entered the value, but when i remove any digit it placed - sign. so what can i do..
I'm sure you're masking it for CNIC :D
Anyways here is my version of masking, it works perfectly:
etusercnic.setRawInputType(InputType.TYPE_CLASS_NUMBER);
etusercnic.addTextChangedListener(new TextWatcher() {
int len = 0;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
String val = etusercnic.getText().toString();
if((val.length()==5 && len <val.length()) || (val.length()==13 && len<val.length())){
etusercnic.append("-");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
String str = etusercnic.getText().toString();
len = str.length();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
The xml of your Edittext should be something similar to this:
<EditText
android:id="#+id/nic_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/signup_cnic_hint"
android:singleLine="true"
android:inputType="date"
android:maxLength="15"
android:textColor="#000000"
android:textColorHint="#808080"
android:textSize="15sp"
/>
Good luck with your project! The easiest way I know to use a mask on EditText in your Android programs in Android Studio is to use MaskedEditText library (GitHub link).
It's a kind of custom EditText with Watcher that allows you to set a hint with different color (if you want if will be available even when user already started to type), mask and it's very easy to use :-)
It's very easy in your case:
compile 'ru.egslava:MaskedEditText:1.0.5'
<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="1234567890"
mask:mask="#####-#######-#"
android:hint="0000000000000"
app:keep_hint="true"
/>
And that is! Good luck!
After some help.. i found a way. Correct Answer...Perfect Working. :)
etusercnic.addTextChangedListener(new TextWatcher() {
int len = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
String str = etusercnic.getText().toString();
len = str.length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String str = s.toString();
String val = etusercnic.getText().toString();
if ((val.length() == 5 && len < val.length()) || (val.length() == 13 && len < val.length())) {
str += "-";
etusercnic.setText(str);
etusercnic.setSelection(str.length());
}
} catch (Exception ignored) {
}
}
#Override
public void afterTextChanged(Editable s) {
}
});

Categories

Resources