I am making a basic text editor app for Android and currently working on formatting the text.
I have an EditText named text_area
where the user types his text and a ToggleButton called bold
that sets the text to bold. Initially, using the EditText.setTypeface
method, all of the text in text_area
would change to bold when the button is on. Using the answer provided in this question, I was able to change only the selected text to bold.
What I really want to do though is that when the button is pressed, all the previously typed text (normal and/or bold) remain unchanged, and whatever the user types next is typed in bold.
Here's my code (Could someone also tell me what the code under the else statement does):
bold.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(bold.isChecked()==true) {
Spannable str = textarea.getText();
if(textarea.getSelectionEnd() > textarea.getSelectionStart())
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
textarea.getSelectionStart(), textarea.getSelectionEnd(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
else
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
textarea.getSelectionEnd(),
textarea.getSelectionStart(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
});
I was stuck on the same issue, and after hours of trying, this is what I came up with.
First, whenever you check the bold/italics whatever styled checkbox you want to apply, you want to get the current cursor position.
both gives you the current cursor position of the EditText if no text is highlighted.
Store this value into a variable.
Then, I overrode the onTextChanged function of the EditText. Since we only want to set span from the last cursor position to the end of wherever change is made, we set the span from lastCursorPosition to the end of the text.
While doing this, I ran into another problem. Whenever I applied another span to another part of the text, previous styles disappeared. I fixed this by creating new StyleSpan for each time a new style was applied. Minimal code to understand:
Full TextArea class I've written:
From MainActivity.java
My very first reply on StackOverflow! Hope this helped :-)