I have an EditText view which I am using to display information to the user. I am able to append a String and it works correctly with the following method:
public void PrintToUser(String text){
MAIN_DISPLAY.append("\n"+text);
}
The application is an RPG game which has battles, when the user is fighting I would like to display the String in RED. So I have attempted to use a SpannableString. (changed the method)
public void PrintToUser(String text, int Colour){
if(Colour == 0){
//Normal(Black) Text is appended
MAIN_DISPLAY.append("\n"+text);
}else{
//Colour text needs to be set.
//Take the CurrentText
String CurrentText = MAIN_DISPLAY.getText().toString();
CurrentText = CurrentText+"\n";
SpannableString SpannableText = new SpannableString(CurrentText + text);
switch(Colour){
case 1:
SpannableText.setSpan(new ForegroundColorSpan(Color.RED), CurrentText.length(), SpannableText.length(), 0);
break;
}
//You cannot append the Spannable text (if you do you lose the colour)
MAIN_DISPLAY.setText(SpannableText, BufferType.SPANNABLE);
}
This new method works and the new line is displayed is red.
Problems
Only the last line formatted is red. If a new line is set to be red the previous formatting is lost due to the way I retrieve the text
String CurrentText = MAIN_DISPLAY.getText().toString();
When I was ONLY appending Strings to the EditText it was displaying the bottom of the EditText box (the last input) now when using SetText the users see's the Top.
Finally My Question:
Is there a way to Append the formatted text?
OR... Can I retrieve the formatted text from the EditText and then when I use .setText I can keep the current format?
AND if so... Is there a way to focus the Display at the Bottom opposed to the Top?
Thank you! Please comment if additional information is needed I've been stuck on this for a while now.
My suggestion would be to use the method:
myTextView.setText(Hmtl.fromHtml(myString));
Where the myString could be of the format:
String myString = "Hello <font color=\'#ff0000\'>World</font>";
The following modifications to PrintToUser() should work..
public void PrintToUser(String text, int Colour){
...
...
Editable CurrentText = MAIN_DISPLAY.getText();
int oldLength = CurrentText.length();
CurrentText.append("\n" + text);
switch(Colour){
case 1:
CurrentText.setSpan(new ForegroundColorSpan(Color.RED),
oldLength, CurrentText.length(), 0);
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With