PhoneUtils equivalent code for edit text - android

Do you have a piece of code to manually format a given phone number in Android? I don't want use PhoneUtils. I need this for a project for my course.

I had a similar issue, please check my code below:
#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));*/
}

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

How to retrieve multi-line text from Edittext?

I want to get a text(Multi-line) from Edittext same as given Screenshot.
I want below output when getText() from Edittext.
Output:
Lorem Ipsum is simply dummy
text of the printing and
typesetting industry. Lorem
Ipsum has been the industry
standard dummy text.
I have tried below solution but, it doesn't work
etMessage.getText().toString().replaceAll("\\n", "<br />")
By default all the EditText widgets in Android are multi-lined. And you can configure the number of lines and the characters types. By setting the input type to multiline do the trick.
<EditText
...
android:inputType="textMultiLine" <!-- Multiline input -->
...
android:lines="8" <!-- Total Lines prior display -->
android:minLines="6" <!-- Minimum lines -->
android:gravity="top|left" <!-- Cursor Position -->
android:maxLines="10" <!-- Maximum Lines -->
android:layout_height="wrap_content" <!-- Height determined by content -->
android:layout_width="match_parent" <!-- Fill entire width -->
android:scrollbars="vertical" <!-- Vertical Scroll Bar -->
/>
After too much searching and waiting for an answer to this question. I have resolved this issue.
Solution:
I have measured each and every line & words for preserve this as Multiline text, you can use below function for that.
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
String result = fitString(ipText, ipText.getText().toString());
private String fitString(EditText editText, String message) {
Log.i(TAG, "fitString: Default String : " + message);
StringBuilder finalMessage = new StringBuilder();
if (isTooLarge(editText, message)) {
Log.i(TAG, "fitString: isTooLarge 1 : " + true);
List<String> lineList = Arrays.asList(message.split("\n"));
Log.i(TAG, "fitString: stringList" + lineList);
if (lineList != null && lineList.size() > 0) {
for (int i = 0; i < lineList.size(); i++) {
if (lineList.get(i) != null && !lineList.get(i).isEmpty()) {
if (isTooLarge(editText, lineList.get(i))) {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + true);
List<String> wordList = Arrays.asList(lineList.get(i).split(" "));
Log.i(TAG, "fitString: wordList" + wordList);
if (wordList != null && wordList.size() > 0) {
Log.i(TAG, "fitString: wordList : " + wordList.size());
StringBuilder temp = new StringBuilder();
String lastWord = "";
for (int j = 0; j < wordList.size(); j++) {
if (wordList.get(j) != null && !wordList.get(j).isEmpty()) {
if (isTooLarge(editText, wordList.get(j))) {
Log.i(TAG, "fitString: isTooLarge 3 : " + wordList.get(j) + " == " + true);
String newString = fitCharacter(editText, wordList.get(j));
Log.i(TAG, "fitString: fitCharacter == " + newString);
if (j == (wordList.size() - 1) && i == (lineList.size() - 1)) {
finalMessage.append(newString);
} else {
finalMessage.append(newString + "\n");
}
} else {
if (j == 0) {
lastWord = wordList.get(j);
} else {
lastWord = " " + wordList.get(j);
}
temp.append(lastWord);
Log.i(TAG, "fitString: temp : " + temp);
Log.i(TAG, "fitString: lastWord : " + lastWord);
if (isTooLarge(editText, temp.toString())) {
temp.setLength(0); // clear String Builder, new StringBuilder()
temp.append(lastWord);
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 1");
finalMessage.append("\n" + lastWord.trim() + "\n");
} else {
Log.i(TAG, "fitString: ###### 2");
finalMessage.append("\n" + lastWord.trim());
}
} else {
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 3");
finalMessage.append(lastWord + "\n");
} else {
Log.i(TAG, "fitString: ###### 4");
finalMessage.append(lastWord);
}
}
Log.i(TAG, "fitString: finalMessage : " + finalMessage);
}
} else {
Log.e(TAG, "fitString: Word is Null or Empty.");
finalMessage.append(" ");
}
}
} else {
Log.e(TAG, "fitString: wordList is Null or Empty.");
}
} else {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + false);
if (i == (lineList.size() - 1)) {
finalMessage.append(lineList.get(i));
} else {
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: Line is Null or Empty.");
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: stringList is Null or Empty.");
finalMessage.append("");
}
return finalMessage.toString();
} else {
Log.i(TAG, "fitString: isTooLarge : " + false);
return message;
}
}
public String fitCharacter(EditText editText, String message) {
Log.i(TAG, "fitCharacter2: Default Word : " + message);
StringBuilder finalWord = new StringBuilder();
int startIndex = 0;
int endIndex = 1;
for (; ; ) {
String tempSplitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " tempSplitWord : " + tempSplitWord);
if (!isTooLarge(editText, tempSplitWord)) { // isTooLarge
if (endIndex < message.length()) {
endIndex = endIndex + 1;
Log.i(TAG, "IF fitCharacter2: endIndex < message.length() " + endIndex + " < " + message.length());
} else {
String result = finalWord.append(tempSplitWord).toString();
Log.i(TAG, "IF RETURN RESULT : " + result);
return result;
}
} else {
endIndex = endIndex - 1;
String splitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " splitWord : " + splitWord);
boolean isTooLarge = isTooLarge(editText, splitWord);
if (!isTooLarge) {
finalWord.append(splitWord + "\n");
}
startIndex = endIndex;
endIndex = endIndex + 1;
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex);
}
}
}
private boolean isTooLarge(EditText editText, String newText) {
if (editText != null && editText.getPaint() != null) {
float textWidth = editText.getPaint().measureText(newText);
return (textWidth >= (editText.getMeasuredWidth() - (12 * density))); // editText.getMeasuredWidth();
} else {
return false;
}
}
For next comers, I find the accepted answer overcomplicated for the task. Here is a nice extension code in Kotlin that uses Paint.breakText(). That said, it can probably be simplified further...
fun EditText.getMultilineText(): String {
val maxWidth = (width - paddingLeft - paddingRight).toFloat()
val original = text.toString().trim()
val len = original.length
val multiline = mutableListOf<String>()
var p = 0
var count = -1
while (count != 0) {
count = paint.breakText(original, p, len, true, maxWidth, null)
if (p + count < len) {
var tmp = count
while (tmp > 0 && original[p + tmp - 1] != ' ') {
tmp -= 1
}
if (tmp > 0) {
count = tmp
}
}
val tmp = original.substring(p, p + count).trim()
if (tmp.isNotBlank()) {
multiline.add(tmp)
}
p += count
}
return multiline.joinToString("\r\n")
}
did you try this one
message = etMessage.getText().toString().replaceAll("\\n", "<br />")
please see this also How can I preserve line breaks from EditText?

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

Android: NullPointerException in onTextChanged() method with EditText

Hello Android developer,
i keep getting a NullPointerException in my onTextChanged() method when EditText changes its text. BUT not on all smartphones. LG G2 does not throw any errors, but eg Samsung Galaxy S 4 does. I have two EditTexts. By entering numbers the program takes both values and calculates something. And really strange is that when the keyboard opens and i press any key and then DEL-key everything works.
here some code:
EditText bestellt = new EditText(this);
bestellt.setInputType(InputType.TYPE_CLASS_NUMBER);
bestellt.setGravity(Gravity.CENTER_HORIZONTAL);
bestellt.setEms(3);
bestellt.setTextAppearance(this, android.R.style.TextAppearance_Medium);
bestellt.setBackgroundColor(Color.parseColor("#DBF2FC"));
bestellt.setHint(Html.fromHtml("<small><small><small>" +
"Bestellt" + "</small></small></small>"));
//bestellt.setOverScrollMode(View.OVER_SCROLL_NEVER);
bestellt.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_FLAG_NAVIGATE_NEXT);
tempTableRow.addView(bestellt);
bestellt.setId(Integer.parseInt(Integer.toString(runde) + "90" + Integer.toString(i + 1) + "90" + Integer.toString(viewTeilID)));
//wieVieleReihen1 = tabellenLayout.getChildCount() - 1;
//scrollViewHor.setSmoothScrollingEnabled(false);
bestellt.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
viewEditText1 = v;
/*if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
//Toast.makeText(getBaseContext(), "Done gedrueckt", Toast.LENGTH_SHORT).show();
return true;
}*/
return false;
}
});
bestellt.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) {
//Toast.makeText(getBaseContext(), Integer.toString(v.getId()), Toast.LENGTH_LONG).show();
//int wieVieleReihen = tabellenLayout.getChildCount() - 1;
try{
int id1, id2, id3, tempPZ;
id1 = viewEditText1.getId();
String[] parts = Integer.toString(id1).split("90");
parts[2] = Integer.toString(Integer.parseInt(parts[2]) + 2);
id3 = Integer.parseInt(parts[0] + "90" + parts[1] + "90" + parts[2]);
parts[2] = Integer.toString(Integer.parseInt(parts[2]) - 1);
id2 = Integer.parseInt(parts[0] + "90" + parts[1] + "90" + parts[2]);
//kontrolle.setText("ID1: " + id1 + " ID2: " + id2 + " ID3: " + id3);
//viewEditText1.requestFocus();
/*INSIDE HERE SHOULD NOT BE A MISTAKE
try {//es müssen unbedingt werte eingegeben worden sein
if (false) {
//((EditText) findViewById(id1)).getText().toString().equals("") || ((EditText) findViewById(id1)).getText().toString().trim().length() == 0 || (((EditText) findViewById(id2)).getText().toString().equals("")) || ((EditText) findViewById(id2)).getText().toString().trim().length() == 0
//Toast.makeText(getBaseContext(), "Werte eingeben und bestaetigen!", Toast.LENGTH_SHORT).show();
} else
tempPZ = 0; //keine Ahnung warum
//((EditText) findViewById(id1)).;
tempPZ = berechnePunktzahl(Integer.parseInt(((EditText) findViewById(id1)).getText().toString()), Integer.parseInt(((EditText) findViewById(id2)).getText().toString()));
((TextView) findViewById(id3)).setText(Integer.toString(tempPZ));
int c;
int summe = 0;
int tempoID = 0;
for (c = 0; c < runde; c++) {
tempoID = Integer.parseInt((c + 1) + "90" + parts[1] + "90" + "3");
summe = summe + Integer.parseInt(((TextView) findViewById(tempoID)).getText().toString());
}
((TextView) findViewById(Integer.parseInt("222" + parts[1]))).setText(Integer.toString(summe));
//punktZahlen.add(Integer.parseInt(parts[0])-1,tempPZ);
//Integer sum = 0;
//for ( Integer i : punktZahlen ) {
// sum += i;
//}
//((TextView) findViewById(Integer.parseInt("222"+parts[1]))).setText(Integer.toString(sum));
} catch (Exception e) {
//Toast.makeText(getBaseContext(), "Werte eingeben!", Toast.LENGTH_LONG).show();
}
*/ INSIDE HERE SHOULD NOT BE A MISTAKE
} catch(Exception e){ //this throws NullPointerException
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
This is the error Stacktrace:
07-17 12:41:05.250 32282-32282/com.martins.martin.bestellen E/YOUR_APP_LOG_TAG﹕ I got an error
java.lang.NullPointerException
at com.martins.martin.bestellen.SecondActivity$2.onTextChanged(SecondActivity.java:278)
at android.widget.TextView.sendOnTextChanged(TextView.java:8910)
at android.widget.TextView.setText(TextView.java:4866)
at android.widget.TextView.setText(TextView.java:4716)
at android.widget.EditText.setText(EditText.java:109)
at android.widget.TextView.setText(TextView.java:4691)
at android.widget.TextView.onRestoreInstanceState(TextView.java:4583)
at android.view.View.dispatchRestoreInstanceState(View.java:13722)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.View.restoreHierarchyState(View.java:13700)
at com.android.internal.policy.impl.PhoneWindow.restoreHierarchyState(PhoneWindow.java:1952)
at android.app.Activity.onRestoreInstanceState(Activity.java:983)
at android.app.Activity.performRestoreInstanceState(Activity.java:955)
at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1144)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$1000(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
I hope you will find the problem. Should have to do something with the Keyboard (any Buffer????)
Thanks a lot,
Martin
Now I solved it by simulting a DEL-Keypress programmatically. Its a very bad solution but i could not find the problem...

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)

Categories

Resources