I have an EditText and where user is supposed to enter a time in format: hh:mm
.
When the user has entered the hour I want to add a semicolon to the edit text automatically. I thought of something like an onKeyDown method that checks if the edit text consists of two numbers, in that case add a semicolon. Is this possible? If so, how?
Asked
Active
Viewed 182 times
1

Marat
- 6,142
- 6
- 39
- 67

Simon Andersson
- 751
- 1
- 9
- 29
-
Possible duplicate of [How to use the TextWatcher class in Android?](http://stackoverflow.com/questions/8543449/how-to-use-the-textwatcher-class-in-android) – wake-0 Jan 04 '17 at 12:20
2 Answers
2
You will need to use TextWatcher
that does exactly what you need. Basically it has 3 methods: beforeTextChanged()
, onTextChanged()
, afterTextChanged()
.
First two methods are not used to change text inside of EditText, they are just used to keep track of changes made on text. The last one is the method where we can modify and style text. The code will look something like this:
String text = "";
yourEditText.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) {
// work with editable here and add :
String newValue = editable.toString();
if (newValue.length() > text.length()) {
text = editable.toString();
if (text.length() == 2) {
yourEditText.setText(text + ":");
}
}
else if (newValue.length() < text.length()) {
text = editable.toString();
}
}
});

Marat
- 6,142
- 6
- 39
- 67
-
This worked great. I have one problem tho, if have typed "13:30" and wants to delete it, when I delete the semicolon, it prints out the semicolon again because there are two number after the text changed. I tried searching for this but couldn't find anything that worked, I want something like if(keyCode != KeyEvent.KEYCODE_DEL) – Simon Andersson Jan 04 '17 at 13:07
-
2
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {}
@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)
editText.setText(S+":");
if(s.length() == 5) //(hh:mm) length is 5
editText.setEnabled(false); //it accept only 5 char.
}
});

sasikumar
- 12,540
- 3
- 28
- 48