-1

I want the user to enter the lunch time (4 numbers), but only using numbers. The ":" would be inserted in real time. Example: Inserted "0830" and "08:30" is displayed. I only found with "." and "," for monetary purposes. What is the best way to automatically and in realtime set the ":" between hour and minute? Thanks

XML :

<EditText
 android:id="@+id/lunch"
 android:hint="00:00"
 android:inputType="time"
 android:digits="0123456789:"
 android:maxLength="5"/>
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Jonesg26
  • 13
  • 4

2 Answers2

1

Here try this:

vendorSearchEt.addTextChangedListener(new TextWatcher() {
            int length = 0;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                String str = vendorSearchEt.getText().toString();
                length = str.length();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {               

                String str = vendorSearchEt.getText().toString();
                if(str.length()==2 && length <str.length()){//length check for backspace
                    vendorSearchEt.append(":");
                }

            }
        });
Rahul Singh Chandrabhan
  • 2,531
  • 5
  • 22
  • 33
0

You can refer below code using textwatcher

TextWatcher textWatcherNumber = new TextWatcher() {
    boolean isEdging;

    @Override
    public void afterTextChanged(Editable text) {
        if (isEdging) return;
        isEdging = true;
        StringBuilder sb = new StringBuilder();
        sb.append(Common.parseOnlyNumbers(text.toString()));

        if (sb.length() > 2)
            sb.insert(2, ":");

        text.replace(0, text.length(), sb.toString());
        isEdging = false;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
};
//below is code of common class
public class Common {
    public static String parseOnlyNumbers(String text) {
    return text.replaceAll("[^0-9]","");
    }
}

---- additional details ----

This way you can also limit user to add phone number in format (012)-345-6789-0000
you can replace below stringbuilder code in above function.

if (sb.length() > 0)
    sb.insert(0, "(");
if (sb.length() > 4)
    sb.insert(4, ")-");
if (sb.length() > 9)
    sb.insert(9, "-");
if (sb.length() > 14)
    sb.insert(14, "-");
bhumik
  • 231
  • 2
  • 11