I'm fairly new in the android game, and I'm trying to build a CountDown Timer similar to the android timer.
Here is my code so far, followed by some questions I have
public class TimeTextWatcher implements TextWatcher {
private final int TEXT_HOUR = 0;
private final int TEXT_MINUTE = 1;
private final int TEXT_SECOND = 2;
private EditText Hours;
private EditText Minutes;
private EditText Seconds;
private int Type;
public TimeTextWatcher(EditText h, EditText m, EditText s, int type){
Hours = h;
Minutes = m;
Seconds = s;
Type = type;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Hours.removeTextChangedListener(this);
Hours.setText(String.format("%02d", Integer.parseInt(s.toString())));
Hours.setSelection(Hours.getText().length());
Hours.addTextChangedListener(this);
}
@Override
public void afterTextChanged(Editable s) {
int curr_value;
if (s.toString().equals(""))
curr_value = -1;
else
curr_value = Integer.parseInt(s.toString());
switch(Type){
case TEXT_HOUR:
if (curr_value > 9)
Minutes.requestFocus();
break;
case TEXT_MINUTE:
if (curr_value > 59)
s.replace(0, 2, Integer.toString(59));
if (curr_value > 9)
Seconds.requestFocus();
break;
case TEXT_SECOND:
if (curr_value > 59)
s.replace(0, 2, Integer.toString(59));
break;
default:
Log.d("TimeTextWatcher", "Error in switch case");
}
}
}
As I said, I'm trying to make it behave similarly to the android built in CountDown timer. some information:
- each editText in MainActivity has it's own
addTextChangedListener
with this class. - each editText is limited to 2 chars.
- when I enter number bigger than 9, it changes focus to the next editText
My goals:
- when typing the number '23', I want that first it will show '02' (after pressing '2') with leading zero, and then after pressing '3' - the whole number.
- focus on the next editText regarding the input number, but after pressing on two digits.
I've tried using new DecimalFormat("00")
or setText(String.format("%02d", Integer.parseInt(s.toString())))
, but it gets stuck after pressing one digit.
Hope I was clear enough.. Thanks!