Math Quiz with true and false counters - android

I am implementing a scenario where user inputs an numeric answer in the edit text, which is being compared with addition of two numbers while inputting text using addTextChangeListener. I am trying to calculate true and false counters.
I get true counters perfectly in below code.
etTestAddAnswer.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 (etTestAddAnswer.getText().toString().length() == (String.valueOf((firstDigit + secondDigit)).length())) {
if (etTestAddAnswer.getText().toString().equalsIgnoreCase("")) {
etTestAddAnswer.setError("Left Blank");
YoYo.with(Techniques.Wobble)
.duration(750)
.playOn(tlTestAddAnswer);
} else {
if (Integer.parseInt(etTestAddAnswer.getText().toString()) == (firstDigit + secondDigit)) {
correctCounter += 1;
etTestAddAnswer.setText("");
Toast.makeText(AdditionTestActivity.this, "Correct", Toast.LENGTH_SHORT).show();
if (finalCounter < 10) {
initGame();
} else {
testAddTime.cancel();
//Toast.makeText(AdditionTestActivity.this, "True Answer :" + correctCounter + "\n" + "Wrong Attempts" + falseCounter + "\n" + "Time " + toolbarTimeTestAddition.getText().toString(), Toast.LENGTH_SHORT).show();
}
} else {
YoYo.with(Techniques.RubberBand)
.duration(750)
.playOn(tlTestAddAnswer);
etTestAddAnswer.requestFocus();
falseCounter += 1;
Log.d(TAG, "False Answers: " + falseCounter);
etTestAddAnswer.setError("False Answer, \n Try Again..!!");
}
}
} else if (etTestAddAnswer.getText().toString().length() > (String.valueOf((firstDigit + secondDigit)).length())) {
YoYo.with(Techniques.RubberBand)
.duration(750)
.playOn(tlTestAddAnswer);
etTestAddAnswer.requestFocus();
Log.d(TAG, "onTextChanged: " + falseCounter);
//falseCounter++;
etTestAddAnswer.setError("False Answer, \n Try Again..!!");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
But the false counter is incorrect. Like if i am on fifth question and give my first wrong input, the false counters log is like this:
1
2
3
4
5
It should only increment one. Any ideas??

Related

how to change the string display

how can i change string 980302 to string 98/03/02 in android studio
I have a variable of type string, for example 980302 I want to represent this way 98/03/02 in edittext Is
there a way?
Thanks for helping
This is probably the most trivial way of doing this...
String a = "980302";
String b = "" + a.charAt(0) + a.charAt(1) + "/" + a.charAt(2) + a.charAt(3) + "/" + a.charAt(4) + a.charAt(5);
YOUR_EDIT_TEXT.setText(b);
Or with a loop:
String a = "980302";
String b = "";
int i = 1;
while(i<a.length()){
if(i == 5){
b = b + a.charAt(i-1) + a.charAt(i);
}
else{
b = b + a.charAt(i-1) + a.charAt(i) + "/";
}
i = i + 2;
}
YOUR_EDIT_TEXT.setText(b);
If you're asking to show 980302 as 98/03/02 while typing, then the answer is using textchange event.
mMyEditText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
String str = s.toString();
if(str.length()==2 || str.length()==5){
str+= '/';
//Set str in edittext
}
}
);
a = a.substring(0, 1) + "/" + a.substring(2, 3) + "/" + a.substring(4, 5);

After entering 2 numbers insert a colon(:) in android

edtTxt.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if(s.length() != 0 && s.length() == 2){
String str = s.toString();
str.replaceAll("..(?!$)", "$0:");
edtTxt.setText(str);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
I need to display ":" after 2nd digit that is for example 10:25, maximum length is 5 digits it is edittext.
If i started typing in the edittext 10 after this ":" should be inserted then 10:25 should be displayed in the edittext.
I tried with the above logic not working. can anyone help me. Thanks in advance
After replaceAll you should assign the value to same variable. Its working fine..
public void afterTextChanged(Editable s) {
if(s.length() != 0 && s.length() == 3){
String str = s.toString();
str = str.replaceAll("..(?!$)", "$0:");
edtTxt.setText(str);
edtTxt.setSelection(edtTxt.getText().length()); //cursor at last position
}
}
First of all you ignore the result of str.replaceAll(). The method returns a String.
The if condition can be simplified to s.length() == 2.
And the regex you are using doesn't work.
This will add colon in the EditText after you have entered 2 characters
if (s.length() == 2) {
edtTxt.setText(s.toString() + ":");
}
Kotlin and improved version of the #sasikumar's solution:
private fun formatInput(clock: Editable?) {
if (clock.toString().isNotEmpty()
&& clock.toString().contains(":").not()
&& clock.toString().length == 3
) {
var str: String = clock.toString()
str = str.replace("..(?!$)".toRegex(), "$0:")
etClock.setText(str)
etClock.setSelection(etClock.text.length)
}
}
etClock.addTextChangedListener(
afterTextChanged = {
formatInput(it)
}
)
etClock.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
etClock.setSelection(etClock.text.length)
}
}
etClock.setOnClickListener {
etClock.setSelection(etClock.text.length)
}
And a great explanation of the used Regex: https://stackoverflow.com/a/23404646/421467
Just do it like this
editTextTime.addTextChangedListener {
if(it?.length == 3 && !it.contains(":")){
it.insert(2,":")
}
}
I think the code is clear
if you put 3 number it will add ":" before the 3rd number
and it will check if your 3rd Char it not already :
then it will insert ":" for you

android check edit text field

Ok, how can I setup edit checks for a text field to limit enter to certain characters and length.
Below is something I worked on but if the cursor is in the first position and i hit return it crashed
final EditText editText1 = (EditText)findViewById(R.id.editText9);
editText1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
editText1.setText("a");
editText1.setTag(1);
editText1.setId(idedittext1);
editText1.setBackgroundColor(0xff66ff66);
editText1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
//linear1.addView(editText1);
final String matchCharacters = "abcdefghijklmnopqrstuvwxyz.";
final CharSequence s_saved = "";
editText1.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count)
{
System.out.println("------------------------------------------------------------");
System.out.println("Entry: " + s + " " + s.length() + " " + start + " " + before + " " + count);
if (before == 1)
{
System.out.println("return");
}
if (s.length() > 4)
{
System.out.println("onTextChanged >4 replaced : " + s + " " + start + " " + before + " " + count);
String replaceStr = s.toString().substring(0, s.length() - 1);
editText1.setText(replaceStr);
editText1.setSelection(s.length() - 1);
}
if (s.length() > 0 && before != 1)
{
Integer sfound = 0;
String sstr = s.toString();
char[] sArray = sstr.toCharArray();
char[] mArray = matchCharacters.toCharArray();
System.out.println("sarray-marray " + " " + sstr + "-" + matchCharacters);
for (char sc : sArray) {
System.out.println("It worked1 " + sc);
for (char mc : mArray) {
System.out.println("It worked2 " + " " + sc + "-" + mc);
if (sc == mc) {
//System.out.println("It worked!");
sfound = sfound + 1;
} else {
//System.out.println("It did not work!");
}
}
}
System.out.println("slength-sfound " + " " + s.length() + "-" + sfound);
if (s.length() == sfound) {
System.out.println("MATCHED!");
} else {
System.out.println("NOMATCH!");
String replaceStr = s.toString().substring(0, s.length() - 1);
editText1.setText(replaceStr);
editText1.setSelection(s.length() - 1);
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Your can only enter the following characters: " + matchCharacters);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}
Any help is appreciated.
Thanks
To limit the EditText length
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="10"/>
To prevent certain character from being typed in
final EditText editText = (EditText) findViewById(R.id.edit_text);
final String matchCharacters = "aeiou";
editText.addTextChangedListener(new TextWatcher() {
#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) {
String text = String.valueOf(editText.getText());
boolean edited = false;
for(int i=0; i<matchCharacters.length(); i++){
char toPrevent = matchCharacters.charAt(i);
if(text.indexOf(toPrevent) < 0){
continue;
}
text = text.replace(String.valueOf(toPrevent), "");
edited = true;
}
if(edited){
editText.setText(text);
}
}
});

Using keyListener and textChangedListener together in Android editText

I am trying to use both
editPhoneNumber.setKeyListener(new KeyListener()
and
editPhoneNumber.addTextChangedListener(new TextWatcher()
together but it seems that they block eachother, my editText is no longer editable.
Thanks for any help
Edit:
I am trying to format the input as the user types:
Input:5551112233
Formatted Input: (555) 111 22 33
The formatting part works well but the reason I am trying to add the KeyListener is when the user tries to delete (by pressing on delete key) and when the inputs length becomes -let's say- 12 characters TextChangedListener interrupts the user to delete by always putting a " " at he end of the text. That is why I am trying to disable the TextChangedListener when the input is a delete key.
boolean isResetClicked;
EditText editPhoneNumber;
Button buttonReset;
protected void onCreate(Bundle savedInstanceState)
{
editPhoneNumber = (EditText) findViewById(R.id.editPhoneNumber);
buttonReset = (Button) findViewById(R.id.buttonResetPhoneNumber);
buttonReset.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
isResetClicked = true;
editPhoneNumber.getText().clear();
isResetClicked = false;
}
});
editPhoneNumber.setKeyListener(new KeyListener()
{
#Override
public boolean onKeyUp(View view, Editable text, int keyCode,
KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DEL)
{
isResetClicked = true;
}
else
isResetClicked=false;
return false;
}
#Override
public boolean onKeyOther(View view, Editable text, KeyEvent event)
{
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onKeyDown(View view, Editable text, int keyCode,
KeyEvent event)
{
return false;
}
#Override
public int getInputType()
{
// TODO Auto-generated method stub
return 0;
}
#Override
public void clearMetaKeyState(View view, Editable content,
int states)
{
// TODO Auto-generated method stub
}
});
editPhoneNumber.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
String str;
if (!isResetClicked)
{
if (s.length() == 0)
{
editPhoneNumber.setText("(");
}
if (s.length() == 1)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText("(" + str);
editPhoneNumber.setSelection(editPhoneNumber.getText()
.length());
}
if (s.length() == 4)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + ") ");
editPhoneNumber.setSelection(editPhoneNumber.getText()
.length());
}
if (s.length() == 9)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber.getText()
.length());
}
if (s.length() == 12)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber.getText()
.length());
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s)
{
}
});
Edit 2:
Even if I'm still unable to understand why two event listeners block my edittext, I solved my problem by modifying the code:
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
String str;
/*Log.i("ED",
"LengthBefore before (lengthBefore = lengthAfter;): "
+ String.valueOf(lengthBefore));*/
lengthBefore = lengthAfter;
lengthAfter = s.length();
/*Log.i("ED",
"LengthBefore after (lengthBefore = lengthAfter;): "
+ String.valueOf(lengthBefore));*/
if ((lengthBefore < lengthAfter) || lengthBefore == 0)
{
if (!isResetClicked)
{
if (s.length() == 0)
{
editPhoneNumber.setText("(");
}
if (s.length() == 1)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText("(" + str);
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 4)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + ") ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 9)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 12)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
}
}
lengthAfter = s.length();
/*Log.i("ED", "LengthAfter after (lengthAfter = s.length();): "
+ String.valueOf(lengthAfter));
Log.i("ED", "LengthBefore: " + String.valueOf(lengthBefore));
Log.i("ED", "LengthAfter: " + String.valueOf(lengthAfter));*/
}
As when the user tries to delete a character the new length will be shorter than the older one. So I prevented the code from checking the length by:
if ((lengthBefore < lengthAfter) || lengthBefore == 0)

Automatically add dash in phone number in Android

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]", "");
}
}

Categories

Resources