Sam
Sam

Reputation: 95

Android - Override user edittext input and add characters towards a specific text?

So I'm currently trying to achieve the following: I have one big piece of text not stored in my app yet. I will have one big EditText and what I want to do is when a user touches any key on the keyboard, a part of my text (like 2 or 3 characters at the time) should appear in the EditText. Then when a user touches a key again, another 2 or 3 characters of the text should appear inside the EditText. I've thought a lot about it but I can't seem to find the right approach to do it. Where to store my Text and how to code so that the app overrides whatever the user inputs and adds 2 or 3 characters in the EditText according to my text that I need to store somewhere.

Any ideas?

Upvotes: 0

Views: 486

Answers (1)

Thorstenvv
Thorstenvv

Reputation: 5396

Take a look at

http://developer.android.com/reference/android/text/TextWatcher.html

Implement a TextWatcher and check the user input in onTextChanged() to determine the user input. Mark the input the user has made with a Span (which can be any custom object, it is just used to tag the text area), so you can later look it up with Editable#getSpans() in afterTextChanged(), where you can replace the whole span with your override text.

Code idea (untested):

onTextChanged(CharSequence s, int start, int before, int count){
    ((Spannable)s).setSpan(new MyMarkObject(), start, start+count, Spannable.SPAN_MARK_MARK) 
}

afterTextChanged(Editable s)
{
    MyMarkObject[] markers = s.getSpans(0, s.length(), MyMarkObject.class);
    for (MyMarkObject marker: markers){
       int start = s.getSpanStart(marker);
       int end = s.getSpanEnd(marker);
       s.replace(start, end, getYourDesiredReplacementTextFor(s.subSequence(start,end));
    }
}

Upvotes: 1

Related Questions