Automatically add colon to Edittext - android

I want to add a mac address to my database via EditText.
Is it possible to add a colon (:) after every second character?
The colon should be displayed directly in the EditText.
EDIT: Tried it. And I think I am on the right way ( your anwers confirm this :P )
inputMac = (EditText) view.findViewById(R.id.editText_mac);
inputMac.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 (s.length() == 2 || s.length() == 5 || s.length() == 7 || s.length() == 9 || s.length() == 12 ){
inputMac.setText(inputMac.getText() + ":");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
But now after 12 characters I get e.g. 123456789123:::::

I've already answered a similar question, so this is how you can achieve it:
String mTextValue;
Character mLastChar = '\0'; // init with empty character
int mKeyDel;
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean flag = true;
String eachBlock[] = myEditText.getText().toString().split(":");
for (int i = 0; i < eachBlock.length; i++) {
if (eachBlock[i].length() > 6) {
flag = false;
}
}
if (flag) {
myEditText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
mKeyDel = 1;
return false;
}
});
if (mKeyDel == 0) {
if (((myEditText.getText().length() + 1) % 3) == 0) {
myEditText.setText(myEditText.getText() + ":");
myEditText.setSelection(myEditText.getText().length());
}
mTextValue = myEditText.getText().toString();
} else {
mTextValue = myEditText.getText().toString();
if (mLastChar.equals(':')) {
mTextValue = mTextValue.substring(0, mTextValue.length() - 1);
myEditText.setText(mTextValue);
myEditText.setSelection(mTextValue.length());
}
mKeyDel = 0;
}
} else {
myEditText.setText(mTextValue);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (s.length()>0) {// save the last char value
mLastChar = s.charAt(s.length() - 1);
} else {
mLastChar = '\0';
}
}
#Override
public void afterTextChanged(Editable s) {}
});
PS: It also handle deleting characters.

I tried I think I found a way wich is not that complicated. (Its not perfect but I think I will make it)
inputMac.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
macLengthBefore = inputMac.length();
Log.d("Textlänge BEFORE", macLengthBefore.toString());
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
macLengthAfter = inputMac.length();
Log.d("Textlänge AFTER", macLengthAfter.toString());
if (macLengthAfter > macLengthBefore && ((inputMac.getText().length() + 1) % 3 == 0) && inputMac.length() <= 15) {
inputMac.setText(inputMac.getText() + ":");
inputMac.setSelection(inputMac.getText().length());
}
}
});
Thanks #Rami for modulo query

After few trial and errors I was able to write a simple and working code:
mEditText.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) {
if ((s.toString().length() < 17) && ((before == 1 && count == 2) || (before == 4
&& count == 5))) {
String string = mEditText.getText().toString();
string = string.concat(":");
mEditText.setText(string);
mEditText.setSelection(string.length());
}
}
});
Below code goes into your xml file:
<EditText
android:id="#+id/edit_text"
style="#style/textfield_wh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="17"
android:digits="abcdefABCDEF0123456789:"
android:inputType="text" />

Try this,
editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
*****APPLY YOUR LOGIC HERE*****
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}

Related

Cyclical replacement the content of EditText with the limited length

For example, I have EditText with length limitation of two characters. When the first and second letters entered it's ok. But when we will try to enter a third letter the first letter should be replaced with it. Next letter should replace the second and so on in a circle. How can I do this one.
Try using TextWatcher on your edit text to achieve the goal
editText.addTextChangedListener(new TextWatcher() {
private int lastModifiedIndex = 1;
#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 (s.length() > 2) {
char toReplace = s.charAt(s.length() - 1);
if (lastModifiedIndex == 0) {
editText.setText("" + s.charAt(lastModifiedIndex) + toReplace);
lastModifiedIndex = 1;
editText.setSelection(s.length());
} else {
editText.setText("" + toReplace + s.charAt(lastModifiedIndex));
lastModifiedIndex = 0;
editText.setSelection(s.length());
}
} else {
lastModifiedIndex = 1;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Try this one
editText.addTextChangedListener(new TextWatcher() {
private int charLimit = 5;
private int position = 5;
private String newSequence;
#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 (s.length() > charLimit ) {
if (position == charLimit) {
newSequence = s.subSequence(s.length()-1, s.length()).toString() +
s.subSequence(1, charLimit);
position = 1;
} else {
position++;
newSequence = s.subSequence(0, position).toString() +
s.subSequence(position+1, s.length());
}
editText.setText(null);
editText.setText(newSequence);
editText.setSelection(position);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});

Android: Using DecimalFormat in TextWatcher with Edittext

I have a problem with using decimal format in textwatcher.
If I don't use DecimalFormat in TextWatcher, there is no problem in the program.
I can delete and set all edittext (above codes/photo left)
But if I use, the program stops.(below codes/photo right)
For example, when I enter the value in the first edittext and go to the second edittext, the program stops.
I also tried the code in afterTextChanged and try-catch but there was no change.
How can i solve this problem?
the_photo
etType5.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (getCurrentFocus() == etType5) {
if (etType5.length() != 0) {
double minute = Double.parseDouble(etType5.getText().toString());
double second = minute * 60.0;
etType6.setText(String.valueOf(second));
} else {
etType6.setText("");
}
}
}
public void afterTextChanged(Editable s) {
}
});
etType6.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (getCurrentFocus() == etType6) {
if (etType6.length() != 0) {
double second = Double.parseDouble(etType6.getText().toString());
double minute = second * 0.016666667;
etType5.setText(String.valueOf(minute));
} else {
etType5.setText("");
}
}
}
public void afterTextChanged(Editable s) {
}
});
etType5.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
DecimalFormat df = new DecimalFormat("#.###");
if (getCurrentFocus() == etType5) {
if (etType5.length() != 0) {
double minute = Double.parseDouble(etType5.getText().toString());
double second = minute * 60.0;
etType6.setText(df.format(second));
} else {
etType6.setText("");
}
}
}
public void afterTextChanged(Editable s) {
}
});
etType6.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
DecimalFormat df = new DecimalFormat("#.###");
if (getCurrentFocus() == etType6) {
if (etType6.length() != 0) {
double second = Double.parseDouble(etType6.getText().toString());
double minute = second * 0.016666667;
etType5.setText(df.format(minute));
} else {
etType5.setText("");
}
}
}
public void afterTextChanged(Editable s) {
}
});

Want to format the number in EditText

I want to format the input which is in the form of number in EditText.The format is 01-133134-124. I wanted first - after 2 number then next dash after 6 numbers.I tried but whenever I pressed delete/backspace because of the wrong entry the format stopped working and no dash is placed after input of 2 number or 6 numbers.Here is the code.Where Enrollement is the EditText field.
Format : 2digitnumber-6dignumber-3dignumber
Enrollement.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Enrollement.setOnKeyListener(new View.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 = Enrollement.getText().length();
if (len == 2) {
int leng = Enrollement.getText().length();
if(leng==2) {
Enrollement.setText(Enrollement.getText() + "-");
Enrollement.setSelection(Enrollement.getText().length());
}
} else if (len == 9) {
int leng = Enrollement.getText().length();
if(leng==9) {
Enrollement.setText(Enrollement.getText() + "-");
Enrollement.setSelection(Enrollement.getText().length());
}
}
} else {
keyDel = 0;
}
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
});
It would be much easier if you changed your approach a bit. You could be always analyzing unformatted verion of your string after every single change in your EditText.
Try this (remember to set android:maxLength="13" for your EditText):
Enrollement.addTextChangedListener(new TextWatcher() {
final int[] blockLengths = new int[]{2, 6, 3};
String mUnformatted = "";
#Override
public void onTextChanged (CharSequence s,int start, int before, int count){
String unformattedSeq = s.toString().replace("-", "");
if (mUnformatted.length() == unformattedSeq.length()) {
return; //length of text has not changed
}
mUnformatted = unformattedSeq;
//formatting sequence
StringBuilder formatted = new StringBuilder();
int blockIndex = 0;
int currentBlock = 0;
for (int i = 0; i < mUnformatted.length(); ++i) {
if (currentBlock == blockLengths[blockIndex]) {
formatted.append("-");
currentBlock = 0;
blockIndex++;
}
formatted.append(mUnformatted.charAt(i));
currentBlock++;
}
Enrollement.setText(formatted.toString());
Enrollement.setSelection(formatted.length());
}
#Override
public void beforeTextChanged (CharSequence s,int start, int count, int after){
}
#Override
public void afterTextChanged (Editable s){
}
});
This code should work correctly. You could only improve the setSelection part (currently if you delete a number in the middle of your EditText it will move your cursor to the end of the text).
In your onTextChanged method you could do:
String str = YourEditText.getText().toString();
if((str.length()==2 && len <str.length()) || (str.length()==6 && len <str.length())){
YourEditText.append("-"); }
Also,
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
String str = YourEditText.getText().toString();
len = str.length();
}
Adapted from this article.

How can i detect ENTER pressed without using OnkeyListner

I am having a problem with the on key listener, which i have completely explained here Unable to get line number on press of ENTER
Now if i am using a textwatcher to implement certain functionalities on my edittext, i need the line number everytime when my cursor moves to the next line. i want to know when the ENTER key is pressed, how can i do that
here is the code of textwatcher
scene.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//here is your code
strcheck = s.toString().substring((s.length()-1),s.length());
if (nowUpper)
strcheck = strcheck.toUpperCase();
else if (nowLower)
strcheck = strcheck.toLowerCase();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if (nowUpper){
if(ix==1)
{
if(strcheck=="\n")
strcheck="a";
Log.v(strcheck, strcheck);
ix=0;
scene.setText(scene.getText().toString().substring(0,scene.length()-1) + strcheck);
scene.setSelection(scene.getText().length());
}
else
{
ix=1;
}
// TODO Auto-generated method stub
}
}
});
try this TextWatcher:
TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
checkForNewLine(s, start, count, "new line entered");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
checkForNewLine(s, start, count, "new line deleted");
}
#Override
public void afterTextChanged(Editable s) {
}
private void checkForNewLine(CharSequence s, int start, int count, String msg) {
int end = start + count;
for (int i = start; i < end; i++) {
if (s.charAt(i) == '\n') {
Log.d(TAG, msg);
}
}
}
};
You can add OnKeyListener for your EditText:
myEdit.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_ENTER) {
int currentLine = getCurrentLine(myEdit);
}
return false;
}
});
private int getCurrentLine(EditText editText) {
int lineNumber = 0;
String text = editText.getText().toString()
.substring(0, editText.getSelectionStart());
for (int i = 0; i < text.length(); i++) {
if (String.valueOf(text.charAt(i)).equalsIgnoreCase("\n")) {
lineNumber++;
}
}
return lineNumber;
}

How to delete instantly SPACE from an edittext if a user presses the space?

I have an edittext, and a textwatcher that watches if SPACE arrived or not. If its a SPACE I would like to delete that instantly. Or if its a space I want to make sure it doesnt appear but indicate somehow (seterror, toast) for the user that space is not allowed.
edittext.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) {}
});
I cannot define onkeydown in the afterTextChaned method, since it gives me an error.
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_SPACE) {
}
}
So it is not working (syntax error, misplaced construct for the int keyCode.
Thanks you in advance!
The solution is as usually much simpler:
#Override
public void afterTextChanged(Editable s) {
String result = s.toString().replaceAll(" ", "");
if (!s.toString().equals(result)) {
ed.setText(result);
ed.setSelection(result.length());
// alert the user
}
}
This shouldn't have the problems of the previous attempts.
setSelection is there to set the cursor again at the end of your EditText:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {}
#Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {}
#Override
public void afterTextChanged(Editable arg0) {
if(editText.getText().toString().contains(" ")){ editText.setText(editText.getText().toString().replaceAll(" " , ""));
editText.setSelection(editText.getText().length());
Toast.makeText(getApplicationContext(), "No Spaces Allowed", Toast.LENGTH_LONG).show();
}
}});
boolean editclicked =false ;
edittext.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
editclicked = false ;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
editclicked = true;
});
Put this as a separate function:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (editclicked) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
return false
}
} else {
super.onKeyDown(keyCode, event);
}
}
#Override
public void afterTextChanged(Editable s) {
String result = s.toString().replaceAll("\\s", "");
if (!s.toString().equals(result)) {
int pos = editText.getSelectionStart() - (s.length() - result.length());
editText.setText(result);
editText.setSelection(Math.max(0,Math.min(pos, result.length())));
editText.setError("No spaces allowed");
}
}
\s matches any whitespace character (equal to [\r\n\t\f\v ])
Setting selection like this, allow you to enter or paste text in middle of edittext without loosing cursor position
My relatively simple solution for instant whitespace deletion without removing spannables (styles) in EditText:
Remove at start:
#Override
public void afterTextChanged(Editable s) {
int i;
for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
s.replace(0, i, "");
}
Basically that's it, but you can also do:
Remove at start (without interrupting first input):
#Override
public void afterTextChanged(Editable s) {
String text = s.toString();
if(!text.trim().isEmpty()){
int i;
for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
s.replace(0, i, "");
}
}
Removing at start and end (allow 1 whitespace at end for convinient input):
#Override
public void afterTextChanged(Editable s) {
int i;
//remove at start
for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
s.replace(0, i, "");
//remove at end, but allow one whitespace character
for (i = s.length(); i > 1 && Character.isWhitespace(s.charAt(i-1)) && Character.isWhitespace(s.charAt(i-2)); i--) { ; }
s.replace(i, s.length(), "");
}
For removing the space instantly you can achieve it by two ways.
One simple solution you can set the digits to your edit text.
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
second way you can set a filter
EditText.setFilters(new InputFilter[] { filter });
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.isSpaceChar(source.charAt(i))) {
return "";
}
}
return null;
}
}
One more simple way to achieve this using the input Filter
editText.setFilters(new InputFilter[]{new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.toString().equalsIgnoreCase(" ")){
return "";
}
return source;
}
}});
This will remove the space entered by the user immediately and gives appearance like space is disabled.

Categories

Resources