basviccc
basviccc

Reputation: 35

Textwatcher android

I have a TextWatcher on my android app. Problem is I want it to listen on every text change, and append a string of the same TextView.

For example, a user inputs A1A2A3A4A5A6A7A8A9 on the EditText field, then I want a textview right on top to hyphenate after 6 characters. so the text view dispalys A1A2A3-A4A5A6-A7A8A9, while the edit text still diplays A1A2A3A4A5A6A7A8A9

I tried this on aftertextchanged, and it did not work:

    @Override
public void afterTextChanged(Editable s) {

    String hyphenated = "";


    if (s.length() == 6)
    {
        hyphenated = s.toString()+"-";
        mCounter.setText(hyphenated);
    }

    if (s.length() == 12)
    {
        hyphenated = s.toString()+"-";
        mCounter.setText(hyphenated);
    }

}

Upvotes: 2

Views: 61

Answers (1)

Yupi
Yupi

Reputation: 4470

For example:

    String myString = "A1A2A3A4A5A6A7A8A9";
    StringBuilder str = new StringBuilder(myString);
    for(int i = 0; i < str.length(); i++){
        if(i == 6){
            str.insert(i, "-");
        }
        if(i == 13){
            str.insert(i, "-");
        }
    }
    System.out.println(str.toString());

Output would be: A1A2A3-A4A5A6-A7A8A9

Upvotes: 1

Related Questions