I'm working on a rich text editor in Android. Basically it has bold, italics and link buttons that are tied to an EditText to change the style of the content. I have it working great if you select the text you want to style first, and then select the button using this method: http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext.
What I'm trying to do is have it work like a rich text editor, where you can use the buttons as a toggle to style the text for as long as you'd like, then click the toggle again to stop using the style. So if I wanted to type 'Pay attention to this!' in bold, I would click the 'B' button, then start typing the text and everything I type would be bold until I click the 'B' button again.
Any ideas on how to pull this off? I hope I've been clear enough :)
For those interested, I got this to work by saving the cursor location ('styleStart' variable below) when the ToggleButton was pressed, and then as the user types more characters, I actually remove the matching StyleSpan with removeSpan(), then re-add it back with setSpan() by using the saved original cursor location + the length of characters currently typed.
You also need to track if the user changes cursor position so that you don't style text that you don't want to. Here's the TextWatcher code:
And here's one of the ToggleButton click actions:
There may be a better solution, happy to hear it if you have one!
There is an open source EditText rich text editor called android-richtexteditor but the code was inexplicably deleted in r5. The code is still there in older revisions; just use svn to check out r4 or earlier to access it. The code appears to support italics, underline, color picker, text size, and more.
Also answered in these questions: 1, 2
You could just update the style after every character that they type using a
TextWatcher
and theaddTextChangedListener()
method.Ok, this is just the bare bones example code.
Just one possibility, not sure it's the best solution but its what comes to mind, and who knows but that it will inspire you to a more elegant solution:
Maybe you could consider internally tracking a hierarchical style structure of the "document", with all its style tags, and reconstructing / replacing the final output with each character typed? Of course you'll have to track cursor position too.
I know this is an old thread, but my coworker spotted DroidWriter on the web. I've played with it a bit and it's pretty self explanatory and very easy to use and modify. Hope this helps anyone who's looking to create a rich text editor.