eText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
int wordvalue = 0;
int numvalue = 0;
for(int i=0; i<s.length(); i++) {
wordvalue += this.calcCharValue(s.charAt(i));
numvalue = this.calcCharValue(s.charAt(i));
String userEntered = nText.getText().toString();
userEntered = userEntered + numvalue;
tv.setText(String.valueOf(wordvalue));
nText.setText(String.valueOf(userEntered));
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
protected int calcCharValue(char a) {
Character ch = new Character(a);
if(ch >= 'A' && ch <= 'Z') { // a=1, b=2, c=3, ..., z=26
Character ca = new Character('A');
return ch.charValue() - ca.charValue() + 1;
}
I am try to create an app that get the text value from the word.
for example
a = 1, b = 2,
I am able to add them like abc = 6, abcd = 10
Now what my problem is I try this value as
abc = 123 and abcde = 12345
but what I get is
abc = 112123 and abcde = 1 12 123 1234 12345
It repeat the every character before and then add next value so how can I handle this repeated problem.
Related
In android edit text, how to separate 10 digit number input by space? I am using android text watcher and I am trying to input multiple 10 digit numbers in the field. The issue arises when multiple numbers are copied and pasted in the field and that time, it doesn't take those spaces. Kindly let me know a solution in order to allow multiple number input with a space after every 10 digit number, when the number is copied from other place.
This will work for both type and copy/paste from other place.
yourEditText.addTextChangedListener(new TextWatcher() {
private static final char space = ' ';
#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) {
int pos = 0;
while (true) {
if (pos >= s.length()) break;
if (space == s.charAt(pos) && (((pos + 1) % 11) != 0 || pos + 1 == s.length())) {
s.delete(pos, pos + 1);
} else {
pos++;
}
}
pos = 10;
while (true) {
if (pos >= s.length()) break;
final char c = s.charAt(pos);
if (Character.isDigit(c)) {
s.insert(pos, "" + space);
}
pos += 11;
}
}
});
Edit and Use the following code as per your needs
StringBuilder s;
s = new StringBuilder(yourTxtView.getText().toString());
for(int i = 10; i < s.length(); i += 10){
s.insert(i, " "); // this line inserts a space
}
yourTxtView.setText(s.toString());
and when you need to get the String without spaces do this:
String str = yourTxtView.getText().toString().replace(" ", "");
I was implemented like after 4 digits hyphen display automatically like(2015-07) in edittext. my code works fine, but problem is while i delete before 4 digits value and again type it not working. addTextChangedListener not trigger when i edidtext retype like 2015-07 to 2014-07. But while i using "/" instead of "-" i can retype value. What is the problem?
mEdtProductionCode.addTextChangedListener(new TextWatcher() {
int prevL = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
prevL = mEdtProductionCode.getText().toString().length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
int length = s.length();
if ((prevL < length) && length == 4) {
String data = mEdtProductionCode.getText().toString();
mEdtProductionCode.setText(data + "-");
mEdtProductionCode.setSelection(length + 1);
}
}
});
You should just move your character checking to the character after the fifth character has been entered, and then chop down String to put the custom character in between:
#Override
public void afterTextChanged(Editable s) {
int length = s.length();
if ((prevL <= length) && length == 5) {
String data = mEditProductionCode.getText().toString();
String beginData = data.substring(0,4);
String endData = Character.toString(data.charAt(length-1));
mEditProductionCode.setText(beginData + "-" + endData);
mEditProductionCode.setSelection(length + 1);
}
}
You can also use data.charAt(length-1) != '-' to check if user manually made dash input, in which case you just ignore and do not make changes to TextEdit.
I want to show the number in this xx-xxx-xxx-xxx-x format on EditText.
Eg (01-140-176-515-4)
I tried modifying the below code which displays the number in credit card number format
(xxxx-xxxx-xxxx-xxxx)
et_cardnumber.addTextChangedListener(new TextWatcher() {
private static final int TOTAL_SYMBOLS = 19; // size of pattern 0000-0000-0000-0000
private static final int TOTAL_DIGITS = 16; // max numbers of digits in pattern: 0000 x 4
private static final int DIVIDER_MODULO = 5; // means divider position is every 5th symbol beginning with 1
private static final int DIVIDER_POSITION = DIVIDER_MODULO - 1; // means divider position is every 4th symbol beginning with 0
private static final char DIVIDER = '-';
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// noop
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
iv_cardtype.setImageResource(getCreditCardTypeForImageView(et_cardnumber.getText().toString()));
}
#Override
public void afterTextChanged(Editable s) {
if (!isInputCorrect(s, TOTAL_SYMBOLS, DIVIDER_MODULO, DIVIDER)) {
s.replace(0, s.length(), buildCorrecntString(getDigitArray(s, TOTAL_DIGITS), DIVIDER_POSITION, DIVIDER));
}
}
private boolean isInputCorrect(Editable s, int totalSymbols, int dividerModulo, char divider) {
boolean isCorrect = s.length() <= totalSymbols; // check size of entered string
for (int i = 0; i < s.length(); i++) { // chech that every element is right
if (i > 0 && (i + 1) % dividerModulo == 0) {
isCorrect &= divider == s.charAt(i);
} else {
isCorrect &= Character.isDigit(s.charAt(i));
}
}
return isCorrect;
}
private String buildCorrecntString(char[] digits, int dividerPosition, char divider) {
final StringBuilder formatted = new StringBuilder();
for (int i = 0; i < digits.length; i++) {
if (digits[i] != 0) {
formatted.append(digits[i]);
if ((i > 0) && (i < (digits.length - 1)) && (((i + 1) % dividerPosition) == 0)) {
formatted.append(divider);
}
}
}
return formatted.toString();
}
private char[] getDigitArray(final Editable s, final int size) {
char[] digits = new char[size];
int index = 0;
for (int i = 0; i < s.length() && index < size; i++) {
char current = s.charAt(i);
if (Character.isDigit(current)) {
digits[index] = current;
index++;
}
}
return digits;
}
});
I couldn't get it right when i make changes to get the format which i want.
Can anyone help me to get the number in xx-xxx-xxx-xxx-x format?
i dont know much in Android , but try to build something like this .
str Yourstring = "";
for (int i = 0; i < digits.length; i++) {
if (i == 2 || i == 5 || i == 8 || i == 11) {
Yourstring = Yourstring + "-" +digits[i];
}
else
{
Yourstring = Yourstring +digits[i];
}
}
I answered this already in this link , please change the logic according to your format
Use this library.
it will allow according yo your formate
EditText Pattern lib
I am developing one application in android for California. now i want to enter Social Security Number in Edit Text in xxx-xx-xxxx format. i have tried following code for achieve the functionality but it is not working fine for clearing the text.. following is my code. any help would be appreciated. i want auto format functionality.
etSocialSecurityNumber.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = etSocialSecurityNumber.getText().toString();
textlength = etSocialSecurityNumber.getText().length();
if(text.endsWith(" "))
return;
if(textlength == 4 || textlength == 7 )
{
etSocialSecurityNumber.setText(new StringBuilder(text).insert(text.length()-1, "-").toString());
etSocialSecurityNumber.setSelection(etSocialSecurityNumber.getText().length());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
This will add a - after every 4 characters and it handels all kind of editing of user, just put your condition for 3 and 2 chars:
edit_text.addTextChangedListener(new TextWatcher() {
private boolean spaceDeleted;
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
CharSequence charDeleted = s.subSequence(start, start + count);
spaceDeleted = " ".equals(charDeleted.toString());
}
public void afterTextChanged(Editable editable) {
edit_text.removeTextChangedListener(this);
int cursorPosition = edit_text.getSelectionStart();
String withSpaces = formatText(editable);
edit_text.setText(withSpaces);
edit_text.setSelection(cursorPosition + (withSpaces.length() - editable.length()));
if (spaceDeleted) {
edit_text.setSelection(edit_text.getSelectionStart() - 1);
spaceDeleted = false;
}
edit_text.addTextChangedListener(this);
}
private String formatText(CharSequence text)
{
StringBuilder formatted = new StringBuilder();
int count = 0;
for (int i = 0; i < text.length(); ++i)
{
if (Character.isDigit(text.charAt(i)))
{
if (count % 4 == 0 && count > 0)
formatted.append("-");
formatted.append(text.charAt(i));
++count;
}
}
return formatted.toString();
}
});
Edited:
userNameET.addTextChangedListener(new TextWatcher() {
private boolean spaceDeleted;
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
CharSequence charDeleted = s.subSequence(start, start + count);
spaceDeleted = "-".equals(charDeleted.toString());
}
public void afterTextChanged(Editable editable) {
userNameET.removeTextChangedListener(this);
int cursorPosition = userNameET.getSelectionStart();
String withSpaces = formatText(editable);
userNameET.setText(withSpaces);
userNameET.setSelection(cursorPosition + (withSpaces.length() - editable.length()));
if (spaceDeleted) {
// userNameET.setSelection(userNameET.getSelectionStart() - 1);
spaceDeleted = false;
}
userNameET.addTextChangedListener(this);
}
private String formatText(CharSequence text)
{
StringBuilder formatted = new StringBuilder();
int count = 0;
if(text.length()==3||text.length()==6)
{
if (!spaceDeleted)
formatted.append(text+"-");
else
formatted.append(text);
}
else
formatted.append(text);
return formatted.toString();
}
});
The following Kotlin code sufficed my requirements
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
backspaced = count == 0
}
override fun afterTextChanged(s: Editable?) {
s?.apply {
if (!isEmpty()) {
if (get(lastIndex) != '-' && (length > 1 && get(lastIndex - 1) != '-') && !backspaced)
count { x -> x.isDigit() }.let { mapOf(3 to 3, 4 to 3, 5 to 6, 6 to 6)[it]?.let { index -> insert(index, "-") } }
else if ((get(lastIndex) == '-' && backspaced) || (lastIndexOf('-') in listOf(0,1,2,4,5,7,8,9,10)) )
delete(length - 1, length)
}
}
}
I know its too late to post an answer here. I just want to share the code which I used to format SSN. Try the following code.
public class SSNFormatter implements TextWatcher{
private boolean mFormatting;
private boolean clearFlag;
private int mLastStart;
private String mBeforeText;
private boolean spaceDeleted;
WeakReference<EditText> mWeakEditText;
public SSNFormatter(WeakReference<EditText> weakEditText) {
this.mWeakEditText = weakEditText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mLastStart = start;
mBeforeText = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (s.length()>0 && mWeakEditText.get().getText().hashCode() == s.hashCode() && mWeakEditText.get().getError() != null)
mWeakEditText.get().setError(null);
if (!mFormatting) {
mFormatting = true;
int curPos = mLastStart;
String beforeValue = mBeforeText;
String currentValue = s.toString();
String formattedValue = formatSSN(s);
if (currentValue.length() > beforeValue.length()) {
int setCusorPos = formattedValue.length()
- (beforeValue.length() - curPos);
mWeakEditText.get().setSelection(
setCusorPos < 0 ? 0 : setCusorPos);
} else {
int setCusorPos = formattedValue.length()
- (currentValue.length() - curPos);
if (setCusorPos > 0
&& !Character.isDigit(formattedValue
.charAt(setCusorPos - 1))) {
setCusorPos--;
}
mWeakEditText.get().setSelection(
setCusorPos < 0 ? 0 : setCusorPos);
}
mFormatting = false;
}
}
private String formatSSN(Editable text){
StringBuilder formattedString = new StringBuilder();
// Remove everything except digits
int p = 0;
while (p < text.length()) {
char ch = text.charAt(p);
if (!Character.isDigit(ch)) {
text.delete(p, p + 1);
} else {
p++;
}
}
// Now only digits are remaining
String allDigitString = text.toString();
int totalDigitCount = allDigitString.length();
if (totalDigitCount == 0 || totalDigitCount > 10) {
// May be the total length of input length is greater than the
// expected value so we'll remove all formatting
text.clear();
text.append(allDigitString);
return allDigitString;
}
int alreadyPlacedDigitCount = 0;
// Only '1' is remaining and user pressed backspace and so we clear
// the edit text.
if (allDigitString.equals("1") && clearFlag) {
text.clear();
clearFlag = false;
return "";
}
boolean chang3 = true;
boolean chang2 = false;
// There must be a '-' inserted after the next 3 numbers
if (chang3 && totalDigitCount - alreadyPlacedDigitCount > 3) {
formattedString
.append(allDigitString.substring(alreadyPlacedDigitCount,
alreadyPlacedDigitCount + 3) + "-");
alreadyPlacedDigitCount += 3;
chang3 = false;
chang2 = true;
}
// There must be a '-' inserted after the next 2 numbers
if (chang2 && totalDigitCount - alreadyPlacedDigitCount > 2) {
formattedString
.append(allDigitString.substring(alreadyPlacedDigitCount,
alreadyPlacedDigitCount + 2) + "-");
alreadyPlacedDigitCount += 2;
chang3 = true;
chang2 = false;
}
// All the required formatting is done so we'll just copy the
// remaining digits.
if (totalDigitCount > alreadyPlacedDigitCount) {
formattedString.append(allDigitString
.substring(alreadyPlacedDigitCount));
}
text.clear();
text.append(formattedString.toString());
return formattedString.toString();
}
}
How can I customize input type of editext shown in the given figure.Basically my requirement is that edittext should show only the last 3 or 4 digits only initial 12 digit should be in password mode.
You need to add a TextWatcher onto the EditText:
int characterCount = 0;
int asteriskCount = 0;
CharSequence input = null;
input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
characterCount = count;
//update input sequence based on changes.
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//update input sequence based on changes.
}
#Override
public void afterTextChanged(Editable s) {
if (asteriskCount != characterCount) {
//make the visible sequence here.
CharSequence seq = "";
for (int i = 0; i < (characterCount <= 12 ? characterCount : 12); i++) {
seq = seq + "*";
}
if (characterCount > 12) {
for (int i = 12; i < characterCount; i++) {
seq = seq + characterCount.charAt(i);
}
}
asteriskCount = characterCount;
input.setText(seq);
}
}
});
There is no built in feature like this. So you have to do it by yourself. You have to make change on the text when the text is changed. To do so .
If you create a custom editText by extending EditText then you can overwrite the onTextChanged method and hanlde the changes.
Or you can use a TextWatcher to hadle changes.
So when the text is changed set the data except last 3 digitst to *.
But remember that you have to use a String field to store original data in a field.
Below is the code snippet of my TextWatcher:
private boolean spaceDeleted;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
characterCount = start;
//update input sequence based on changes.
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// check if a space was deleted
CharSequence charDeleted = s.subSequence(start, start + count);
spaceDeleted = " ".equals(charDeleted.toString());
}
#Override
public void afterTextChanged(Editable s) {
if(s.length()>12){
return;
}
System.out.println("Character Count in afterTextChange->"+characterCount);
System.out.println("Editable Character->"+s);
ccNumber.removeTextChangedListener(this);
// record cursor position as setting the text in the textview
// places the cursor at the end
int cursorPosition = ccNumber.getSelectionStart();
String withSpaces = formatText(s);
ccNumber.setText(withSpaces);
// set the cursor at the last position + the spaces added since the
// space are always added before the cursor
ccNumber.setSelection(cursorPosition + (withSpaces.length() - s.length()));
// if a space was deleted also deleted just move the cursor
// before the space
if (spaceDeleted) {
ccNumber.setSelection(ccNumber.getSelectionStart() - 1);
spaceDeleted = false;
}
// enable text watcher
ccNumber.addTextChangedListener(this);
}
private String formatText(CharSequence s) {
// TODO Auto-generated method stub
StringBuilder formatted = new StringBuilder();
int count = 0;
/* if(s.length()<12){
formatted.append("*");
}else{
formatted.append(s.charAt(characterCount));
}*/
for (int i = 0; i < s.length(); ++i)
{
formatted.append("*");
/*if (Character.isDigit(s.charAt(i)))
{
if (count % 4 == 0 && count > 0)
formatted.append(" ");
formatted.append(s.charAt(i));
++count;
}*/
}
return formatted.toString();
}
});