Viktor
Viktor

Reputation: 656

How to get the same html-string from EditText that i put it there

I try to use html-tags for my text in EditText and I want to save it in Room database. So I created a string with html tags like that:

EditText.setText("Hi <font color="#4B0082">there</font>".parseAsHtml())

It works, but when I try to get it back from the EditText like that:

EditText.text.toHtml()

I get this:

<p dir="ltr">Hi <span style="color:#4B0082;">there</span></p>

Why EditText changes my tags and adds something else? I don't need "p" and "span" tags at all. What am I supposed to do? How to get my original string back from the EditText?

Upvotes: 0

Views: 157

Answers (2)

Cheticamp
Cheticamp

Reputation: 62841

Android views, in general, do not operate directly on HTML tags. When you set the text to the EditText, a translation occurs to Spans. In your example,

"Hi <font color="#4B0082">there</font>"

the font color is translated to a ForegroundColorSpan.

When you try to get the text back from the EditText, a reverse translation occurs and the ForegroundColorSpan is translated to an HTML span tag with a style that specifies the font color. This is equivalent in appearance to the original HTML code.

I assume, since your are placing the text into an EditText, that the text could be changed and what you want is the updated text encoded into the same type of HTML that you placed into the EditText. (If you simply want to retrieve exactly the same string back that you put into the EditText you could try using a View tag).

I think that the only way to get the translation you want is to write your own conversion routine. You can get the spans from the text with getSpans(). You would write something similar to Html.toHtml(). This could be a simple or hard task depending upon how robust the translation needs to be.

There could also be a library that can be customized, but I am unaware of one.

Upvotes: 1

Olena Y
Olena Y

Reputation: 233

Try this one:

String text = Html.toHtml(yourEditText.getText())

It should return you a text with html formatting

Upvotes: 0

Related Questions