1
votes

Mettre une barre oblique dans la date d'un EditText

J'ai lu beaucoup de questions similaires, mais personne ne répond aux miennes ni ne peut résoudre mon problème. J'ai un EditText comme celui-ci dans la mise en page:

  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('/');
                }
            }
        });

J'ai besoin que lorsque l'utilisateur écrit les nombres du mois et de l'année, une barre oblique apparaisse ou disparaisse lorsqu'il écrit. S'il écrit 2 nombres, une barre oblique doit apparaître. S'il efface et son seul numéro, alors la barre oblique doit disparaître.

J'ai besoin que dans le editText apparaisse la date comme: 14/06

Voici mon code mais c'est Ca ne fonctionne pas.

    <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" />

Pour info, j'ai créé une classe pour une solution à ce problème, merci


9 commentaires

changez android: inputType de number à` text` et voyez ce qui se passe.


Salut! Si je fais cela, le clavier se transforme en lettres au lieu de chiffres


Je pense que la date n'est pas un nombre. pourquoi ne pas utiliser un sélecteur de dates à la place?


Salut merci pour votre réponse, car mon patron m'a dit de faire de cette façon. Insérer un numéro avec le clavier numérique


hé, jetez un œil à ce post. je pense que cela pourrait aider: stackoverflow.com/a/16889503/1656813


vous devez masquer votre edittext


Double possible de Entrée masquée à l'aide du widget EditText sous Android


1 linéaire 3 edittext 2 textview pourrait avoir du sens


Consultez ce lien, il peut vous aider: stackoverflow.com/a/56700789/9423249


3 Réponses :


0
votes

Ajoutez votre logique dans onTextChanged au lieu de afterTextChanged

Veuillez essayer le code ci-dessous:

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) {

            }
        });

J'espère son travail pour vous.


1 commentaires

Bonjour, ce n'est pas le cas! écrit beaucoup de barres obliques



4
votes

Utilisez le texte de modification masqué.

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

<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:met_mask="##/##"/>


1 commentaires

Salut, lorsque j'essaie de mettre en œuvre cela, lorsque je compile, affiche cette erreur: La fusion du manifeste a échoué: Attribute application @ appComponentFactory value = (android.support.v4.app.CoreComponentFactory) de [com.android.support:support-compat:28.0 .0] AndroidManifest.xml: 22: 18-91 est également présent sur [androidx.core: core: 1.0.1] AndroidManifest.xml: 22: 18-86 value = (androidx.core.app.CoreComponentFactory). Suggestion: ajoutez 'tools: replace = "android: appComponentFactory"' à l'élément sur AndroidManifest.xml: 6: 5-28: 19 pour remplacer.



0
votes

Merci, après quelques jours, j'ai eu la solution, cette classe:

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;
    }
}


0 commentaires