4

I readed a lot of similar questions, but no one answers mine or can solve my problem. I have a EditText like this in the layout:

    <EditText
        android:id="@+id/editText2"
        android:layout_width="248dp"
        android:layout_height="59dp"
        android:layout_marginStart="21dp"
        android:layout_marginTop="36dp"
        android:width="360dp"
        android:ems="5"
        android:hint="@string/ultimos4Dig"
        android:inputType="number"
        android:maxLength="10"
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

I need that when the user are writing the numers of the month and year, a slash appear or disappearwhen he is writing. If he writes 2 numbers then a slash needs to appear. If he erases and its only one number, then the slash needs to disappear.

I need that in the editText appears the date as: 14/06

Here is my code but its not working.

  protected void onCreate(Bundle savedInstanceState) {

        EditText editText2 = (EditText)  findViewById(R.id.editText2);
        editText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void afterTextChanged(Editable text) {
                if (text.length() == 2) {
                    text.append('/');
                }
            }
        });

FYI i made a class for a solution of this, thanks

Ferchi
  • 100
  • 1
  • 9

4 Answers4

4

Use Masked Edit Text:

https://github.com/santalu/mask-edittext

In Moudle build gradle add:

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

In app build gradle add:

dependencies {
     implementation 'com.github.santalu:maskara:1.0.0'
}

And in your layout you can use MaskEditText:

<com.santalu.maskedittext.MaskEditText
    android:id="@+id/editText2"
    android:layout_width="248dp"
    android:layout_height="59dp"
    android:layout_marginStart="21dp"
    android:layout_marginTop="36dp"
    android:width="360dp"
    android:ems="5"
    android:hint="@string/ultimos4Dig"
    android:inputType="number"
    android:maxLength="10"
    android:textSize="24sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:mask="##/##"/>
MorZa
  • 2,215
  • 18
  • 33
Asif Patel
  • 1,744
  • 1
  • 20
  • 27
  • Hi, when I try to implement this, when I compile shows this error: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91 is also present at [androidx.core:core:1.0.1] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory). Suggestion: add 'tools:replace="android:appComponentFactory"' to element at AndroidManifest.xml:6:5-28:19 to override. – Ferchi Jun 24 '19 at 12:04
2

Add your logic in onTextChanged instead of afterTextChanged

Please try below code :

editText2 .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) {
                String str=editText2 .getText().toString();
                int textLength=editText2 .getText().length();
                if (textLength == 3) {
                    if (!str.contains("/")) {
                        editText2 .setText(new StringBuilder(editText2 .getText().toString()).insert(str.length() - 1, "/").toString());
                        editText2 .setSelection(editText2 .getText().length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

I hope its work for you.

Android Geek
  • 8,956
  • 2
  • 21
  • 35
1

Thanks you, after some days i got the solution, this class:

public class EditMMYY extends AppCompatEditText implements TextWatcher
{
    private String sPrev = "";
    private int iMon = 0;
    private int iYear = 0;

    private void InitValue()
    {
        setInputType(InputType.TYPE_CLASS_NUMBER);
        setFilters(new InputFilter[] {new InputFilter.LengthFilter(5)});
        setHint("MM/YY");
    }

    public EditMMYY(Context context)
    {
        super(context);
        InitValue();
    }

    public EditMMYY(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        InitValue();
    }

    public EditMMYY(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        InitValue();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        // Chequeo que el ingreso sea MM/YY
        String sNew = s.toString();
        int newLen = sNew.length();

        if(sNew.equals(sPrev))
        {
            return;
        }
        switch(newLen)
        {
            case 0:
                iMon = 0;
                iYear = 0;
                sPrev = sNew;
                break;
            case 1:
                iMon  = Integer.parseInt(sNew);
                iYear = 0;
                if(sPrev.length() == 0 && iMon > 1)
                {    // Si se escribe un número mayor que 1, lo tomo como mes
                    sPrev = String.format("%02d/", iMon);
                }
                else
                {
                    sPrev = sNew;
                }
                break;
            case 2:
                iMon  = Integer.parseInt(sNew);
                iYear = 0;
                if(sPrev.length() == 1)
                {
                    // Si ya es un mes válido, lo completo, sino dejo
                    // sPrev sin cambios hasta que se ingrese algo válido
                    if(iMon >= 1 && iMon <= 12)
                    {
                        sPrev = String.format("%02d/", iMon);
                    }
                }
                else
                {
                    sPrev = sNew;
                }
                break;
            case 3:
                iMon  = Integer.parseInt(sNew.substring(0, 2));
                iYear = 0;
                if(sPrev.length() == 2)
                {
                    iMon = Integer.parseInt(sNew.substring(0, 2));
                    iYear = Integer.parseInt(sNew.substring(2, 3));
                    sPrev = String.format("%02d/%d", iMon, iYear);
                }
                else
                {
                    sPrev = sNew;
                }
                break;
            case 4:
            case 5:
                iMon = Integer.parseInt(sNew.substring(0, 2));
                iYear = Integer.parseInt(sNew.substring(3, newLen));
                sPrev = sNew;
                break;
            default:
                sPrev = sNew;
                break;
        }
        setText(sPrev);
        setSelection(sPrev.length());
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {
    }

    @Override
    public void afterTextChanged(Editable s)
    {

    }

    public int getMon()
    {
        return iMon;
    }

    public int getYear()
    {
        return iYear;
    }
}
Ferchi
  • 100
  • 1
  • 9
1

I think this got the solution to some extent. Add app:endIconMode="clear_text" to the TextInputlayout.

 dateOfBirth.getEditText().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) {
                if (charSequence.length() == 2 || charSequence.length() == 5) {
                    if (!Pattern.compile("([0-9]{2})/").matcher(charSequence).matches()) {
                        dateOfBirth.getEditText().setText(new StringBuilder(dateOfBirth.getEditText().getText().toString()).insert(charSequence.length(), "/").toString());
                        dateOfBirth.getEditText().setSelection(dateOfBirth.getEditText().getText().length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });