如何在TextView中显示HTML?

发布于 2024-08-19 07:27:29 字数 192 浏览 2 评论 0原文

我有简单的 HTML

<h2>Title</h2><br>
<p>description here</p>

我想在 TextView 中显示 HTML 样式的文本。如何做到这一点?

I have simple HTML:

<h2>Title</h2><br>
<p>description here</p>

I want to display HTML styled text it in TextView. How to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

满栀 2024-08-26 07:27:29

您需要使用 Html。 fromHtml() 在 XML 字符串中使用 HTML。简单地在布局 XML 中引用带有 HTML 的字符串是行不通的。

应该执行的操作:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else { 
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}

这是您在 Java和 Kotlin 中

textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
    Html.fromHtml(html)
}

You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.

This is what you should do in Java

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else { 
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}

And in Kotlin:

textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
    Html.fromHtml(html)
}
遇见了你 2024-08-26 07:27:29

setText(Html.fromHtml(bodyData)) 在 api 24 之后已弃用。现在您必须执行以下操作:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
      tvDocument.setText(Html.fromHtml(bodyData,Html.FROM_HTML_MODE_LEGACY));
 } else {
      tvDocument.setText(Html.fromHtml(bodyData));
 }

setText(Html.fromHtml(bodyData)) is deprecated after api 24. Now you have to do this:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
      tvDocument.setText(Html.fromHtml(bodyData,Html.FROM_HTML_MODE_LEGACY));
 } else {
      tvDocument.setText(Html.fromHtml(bodyData));
 }
城歌 2024-08-26 07:27:29

看看这个: https://stackoverflow.com/a/8558249/450148

这也相当不错!

<resource>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

它仅适用于少数标签。

Have a look on this: https://stackoverflow.com/a/8558249/450148

It is pretty good too!!

<resource>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

It works only for few tags.

呆头 2024-08-26 07:27:29

如果您希望能够通过 xml 配置它而不需要对 java 代码进行任何修改,您可能会发现这个想法很有帮助。只需从构造函数中调用 init 并将文本设置为 html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

xml:

<com.package.HTMLTextView
android:text="@string/about_item_1"/>

If you want to be able to configure it through xml without any modification in java code you may find this idea helpful. Simply you call init from constructor and set the text as html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

xml:

<com.package.HTMLTextView
android:text="@string/about_item_1"/>
梦里梦着梦中梦 2024-08-26 07:27:29

如果您尝试从字符串资源 ID 显示 HTML,格式可能不会显示在屏幕上。如果您遇到这种情况,请尝试使用 CDATA 标记:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

请参阅此帖子了解更多详细信息。

If you are trying to show HTML from a string resource id, the formatting may not show up on screen. If that is happening to you, try using CDATA tags instead:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

See this post for further details.

执笏见 2024-08-26 07:27:29

我知道这个问题很老了。这里的其他答案建议 Html.fromHtml() 方法。我建议您使用 HtmlCompat.fromHtml() 来自 androidx.core.text.HtmlCompat 包。因为这是 Html 类的向后兼容版本。

示例代码:

import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;

String htmlString = "<h1>Hello World!</h1>";

Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);

TextView tvOutput = (TextView) findViewById(R.id.text_view_id);

tvOutput.setText(spanned);

通过这种方式,您可以避免Android API版本检查,并且易于使用(单行解决方案)。

I know this question is old. Other answers here suggesting Html.fromHtml() method. I suggest you to use HtmlCompat.fromHtml() from androidx.core.text.HtmlCompat package. As this is backward compatible version of Html class.

Sample code:

import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;

String htmlString = "<h1>Hello World!</h1>";

Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);

TextView tvOutput = (TextView) findViewById(R.id.text_view_id);

tvOutput.setText(spanned);

By this way you can avoid Android API version check and it's easy to use (single line solution).

你爱我像她 2024-08-26 07:27:29

下面的代码给了我最好的结果。

TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);

The below code gave best result for me.

TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);
酒废 2024-08-26 07:27:29
String value = "<html> <a href=\"http://example.com/\">example.com</a> </html>";
    SiteLink= (TextView) findViewById(R.id.textViewSite);
    SiteLink.setText(Html.fromHtml(value));
    SiteLink.setMovementMethod(LinkMovementMethod.getInstance());
String value = "<html> <a href=\"http://example.com/\">example.com</a> </html>";
    SiteLink= (TextView) findViewById(R.id.textViewSite);
    SiteLink.setText(Html.fromHtml(value));
    SiteLink.setMovementMethod(LinkMovementMethod.getInstance());
还给你自由 2024-08-26 07:27:29

如果您只想显示一些 html 文本并且实际上并不需要 TextView,那么使用 WebView 并按如下方式使用它:

String htmlText = ...;
webview.loadData(htmlText , "text/html; charset=UTF-8", null);

这并不限制您使用一些html 标签也可以。

If you just want to display some html text and don't really need a TextView, then take a WebView and use it like following:

String htmlText = ...;
webview.loadData(htmlText , "text/html; charset=UTF-8", null);

This does not restrict you to a few html tags either.

丶情人眼里出诗心の 2024-08-26 07:27:29

使用 strings.xml 文件中的字符串的 CData 部分来将 html 内容实际显示到 TextView 的最佳方法是,下面的代码片段将为您提供公平的想法。

//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>

//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));

即使在使用 String.format 方法格式化文本后,字符串文本中的 CData 部分也能保持 html 标签数据不变。因此, Html.fromHtml(str) 工作正常,您将在欢迎消息中看到粗体文本。

输出:

欢迎来到您最喜欢的音乐应用商店。登录身份:用户名

The best approach to use CData sections for the string in strings.xml file to get a actual display of the html content to the TextView the below code snippet will give you the fair idea.

//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>

//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));

CData section in string text keeps the html tag data intact even after formatting text using String.format method. So, Html.fromHtml(str) works fine and you’ll see the bold text in Welcome message.

Output:

Welcome, to your favorite music app store. Logged in as: username

撩动你心 2024-08-26 07:27:29

值得一提的是,该方法 Html.fromHtml( String source) 从 API 级别 24 开始已弃用。如果这是您的目标 API,您应该使用 Html.fromHtml(String source, int flags) 代替。

It's worth mentioning that the method Html.fromHtml(String source) is deprecated as of API level 24. If that's your target API, you should use Html.fromHtml(String source, int flags) instead.

清引 2024-08-26 07:27:29

创建了 Kotlin 扩展来将 htmlString 转换 -

fun String?.toHtml(): Spanned? {
    if (this.isNullOrEmpty()) return null
    return HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_COMPACT)
}

Created Kotlin extensions to convert html from String -

fun String?.toHtml(): Spanned? {
    if (this.isNullOrEmpty()) return null
    return HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_COMPACT)
}
凉风有信 2024-08-26 07:27:29

我还想建议以下项目: https://github.com/NightWhistler/HtmlSpanner

使用率几乎与默认的 android 转换器相同:

(new HtmlSpanner()).fromHtml()

在我开始自己实现 html 到 spannable 转换器之后发现它,因为标准 Html.fromHtml 在渲染控制方面没有提供足够的灵活性,甚至无法使用 ttf 中的自定义字体

I would like also to suggest following project: https://github.com/NightWhistler/HtmlSpanner

Usage is almost the same as default android converter:

(new HtmlSpanner()).fromHtml()

Found it after I already started by own implementation of html to spannable converter, because standard Html.fromHtml does not provide enough flexibility over rendering control and even no possibility to use custom fonts from ttf

吖咩 2024-08-26 07:27:29

通过各种答案建议使用 Html 框架类,如此处建议的那样,但不幸的是,该类在不同版本的 Android 中具有不同的行为以及各种未解决的错误,如问题 2146371477823512875953

因此,您可能希望使用兼容性库来跨 Android 版本标准化和反向移植 Html 类,其中包括更多元素和样式的回调:

Github 项目 HtmlCompat

虽然它与框架的 Html 类类似,但需要进行一些签名更改才能允许更多回调。以下是 GitHub 页面上的示例:

Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0);
// You may want to provide an ImageGetter, TagHandler and SpanCallback:
//Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
//        imageGetter, tagHandler, spanCallback);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);

It has been suggested through various answers to use the Html framework class as suggested here, but unfortunately this class has different behavior in different versions of Android and various unaddressed bugs, as demonstrated in issues 214637, 14778, 235128 and 75953.

You may therefore want to use a compatibility library to standardize and backport the Html class across Android versions which includes more callbacks for elements and styling:

Github project HtmlCompat

While it is similar to the framework's Html class, some signature changes were required to allow more callbacks. Here's the sample from the GitHub page:

Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0);
// You may want to provide an ImageGetter, TagHandler and SpanCallback:
//Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
//        imageGetter, tagHandler, spanCallback);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);
黯然 2024-08-26 07:27:29

简单地使用
输入图像描述这里

checkBoxTextView.text =
        Html.fromHtml("<p><font color=#666666>I agree to</font><font color=#0173B7>  <b><u>Terms & Conditions</u></b></font><font color=#666666> and the <u></font><b><font color=#0173B7>Privacy Policy</font></u></b></font></p>")

simply use
enter image description here

checkBoxTextView.text =
        Html.fromHtml("<p><font color=#666666>I agree to</font><font color=#0173B7>  <b><u>Terms & Conditions</u></b></font><font color=#666666> and the <u></font><b><font color=#0173B7>Privacy Policy</font></u></b></font></p>")
笛声青案梦长安 2024-08-26 07:27:29

简单使用 Html.fromHtml("html string")。这会起作用。如果字符串具有像

这样的标签,那么就会出现空格。但我们无法消除这些空间。如果您仍然想删除空格,则可以删除字符串中的标签,然后将字符串传递给方法 Html.fromHtml("html string"); 。此外,通常这些字符串来自服务器(动态),但不常见,如果在这种情况下,将字符串按原样传递给方法比尝试从字符串中删除标签更好。

Simple use Html.fromHtml("html string"). This will work. If the string has tags like <h1> then spaces will come. But we cannot eliminate those spaces. If you still want to remove the spaces, then you can remove the tags in the string and then pass the string to the method Html.fromHtml("html string"); . Also generally these strings come from server(dynamic) but not often, if it is the case better to pass the string as it is to the method than try to remove the tags from the string.

坏尐絯 2024-08-26 07:27:29

如果您在项目中使用 androidx.* 类,则应使用 HtmlCompat.fromHtml(text, flag)

该方法的来源是:

@NonNull
    public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(source, flags);
        }
        //noinspection deprecation
        return Html.fromHtml(source);
    }

使用 HtmlCompat.fromHtml 比使用 Html.fromHtml 更好,因为代码更少 - 只有一行代码,推荐使用它。

If you use androidx.* classes in your project, you should use HtmlCompat.fromHtml(text, flag).

Source of the method is:

@NonNull
    public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(source, flags);
        }
        //noinspection deprecation
        return Html.fromHtml(source);
    }

It is better to use HtmlCompat.fromHtml than Html.fromHtml as there is less code- only one line of code, and it's recommended way to use it.

逐鹿 2024-08-26 07:27:29

我已经使用网络视图实现了这一点。就我而言,我必须从 URL 加载图像以及文本视图中的文本,这对我有用。

WebView myWebView =new WebView(_context);
        String html = childText;
        String mime = "text/html";
        String encoding = "utf-8";
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);

I have implemented this using web view. In my case i have to load image from URL along with the text in text view and this works for me.

WebView myWebView =new WebView(_context);
        String html = childText;
        String mime = "text/html";
        String encoding = "utf-8";
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
小ぇ时光︴ 2024-08-26 07:27:29
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)
自由如风 2024-08-26 07:27:29

创建一个全局方法,例如:

public static Spanned stripHtml(String html) {
            if (!TextUtils.isEmpty(html)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT);
                } else {
                    return Html.fromHtml(html);
                }
            }
            return null;
        }

您也可以在 Activity/Fragment 中使用它,例如:

text_view.setText(stripHtml(htmlText));

Make a global method like:

public static Spanned stripHtml(String html) {
            if (!TextUtils.isEmpty(html)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT);
                } else {
                    return Html.fromHtml(html);
                }
            }
            return null;
        }

You can also use it in your Activity/Fragment like:

text_view.setText(stripHtml(htmlText));
懷念過去 2024-08-26 07:27:29

人们建议使用 TextView、WebView 和各种解决方案的子类。我想知道为什么没有人提到一个简单的 绑定适配器

@BindingAdapter(value = ["htmlText"])
fun TextView.setHtmlText(string: String?) {
    text = HtmlCompat.fromHtml(string?:"", HtmlCompat.FROM_HTML_MODE_COMPACT)
}

所以你的 TextView xml 看起来像

<TextView
   ...
   htmlText="<p>Your <b>HTML</b> text</p>"
   ... />

People have suggested subclass for TextView, WebView and all sorts of solutions. I wonder why nobody mentioned a simple binding adapter.

@BindingAdapter(value = ["htmlText"])
fun TextView.setHtmlText(string: String?) {
    text = HtmlCompat.fromHtml(string?:"", HtmlCompat.FROM_HTML_MODE_COMPACT)
}

So your TextView xml will look like

<TextView
   ...
   htmlText="<p>Your <b>HTML</b> text</p>"
   ... />
抹茶夏天i‖ 2024-08-26 07:27:29

每当您编写自定义文本视图时,基本的 HTML 设置文本功能都会从某些设备中消失。

所以我们需要执行以下附加步骤 make is work

public class CustomTextView extends TextView {

    public CustomTextView(..) {
        // other instructions
        setText(Html.fromHtml(getText().toString()));
    }
}

Whenever you write custom text view basic HTML set text feature will be get vanished form some of the devices.

So we need to do following addtional steps make is work

public class CustomTextView extends TextView {

    public CustomTextView(..) {
        // other instructions
        setText(Html.fromHtml(getText().toString()));
    }
}
乖乖哒 2024-08-26 07:27:29

只需使用:

String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));

Simply use:

String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));
┾廆蒐ゝ 2024-08-26 07:27:29
public class HtmlTextView extends AppCompatTextView {

public HtmlTextView(Context context) {
    super(context);
    init();
}

private void init(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        setText(Html.fromHtml(getText().toString(), Html.FROM_HTML_MODE_COMPACT));
    } else {
        setText(Html.fromHtml(getText().toString()));
    }
 }
}

上述答案的更新

public class HtmlTextView extends AppCompatTextView {

public HtmlTextView(Context context) {
    super(context);
    init();
}

private void init(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        setText(Html.fromHtml(getText().toString(), Html.FROM_HTML_MODE_COMPACT));
    } else {
        setText(Html.fromHtml(getText().toString()));
    }
 }
}

update of answer above

·深蓝 2024-08-26 07:27:29

使用下面的代码来获得解决方案:

textView.setText(fromHtml("<Your Html Text>"))

Utility Method

public static Spanned fromHtml(String text)
{
    Spanned result;
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(text);
    }
    return result;
}

Use below code to get the solution:

textView.setText(fromHtml("<Your Html Text>"))

Utitilty Method

public static Spanned fromHtml(String text)
{
    Spanned result;
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(text);
    }
    return result;
}
软糖 2024-08-26 07:27:29

您可以使用简单的 Kotlin 扩展函数,如下所示:

fun TextView.setHtmlText(source: String) {
    this.text = HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

用法:

textViewMessage.setHtmlText("Message: <b>Hello World</b>")

You can use simple Kotlin extension function like this:

fun TextView.setHtmlText(source: String) {
    this.text = HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

And usage:

textViewMessage.setHtmlText("Message: <b>Hello World</b>")
韶华倾负 2024-08-26 07:27:29

我可以建议一个有点老套但仍然天才的解决方案吗!我从这篇文章中得到了这个想法并进行了修改对于安卓。基本上,您使用 WebView 并在可编辑的 div 标记中插入要显示和编辑的 HTML。这样,当用户点击 WebView 时,键盘就会出现并允许编辑。您只需添加一些 JavaScript 即可恢复编辑后的 ​​HTML,瞧!

这是代码:

public class HtmlTextEditor extends WebView {

    class JsObject {
        // This field always keeps the latest edited text
        public String text;
        @JavascriptInterface
        public void textDidChange(String newText) {
            text = newText.replace("\n", "");
        }
    }

    private JsObject mJsObject;

    public HtmlTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        getSettings().setJavaScriptEnabled(true);
        mJsObject = new JsObject();
        addJavascriptInterface(mJsObject, "injectedObject");
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadUrl(
                        "javascript:(function() { " +
                            "    var editor = document.getElementById(\"editor\");" +
                            "    editor.addEventListener(\"input\", function() {" +
                            "        injectedObject.textDidChange(editor.innerHTML);" +
                            "    }, false)" +
                            "})()");
            }
        });
    }

    public void setText(String text) {
        if (text == null) { text = ""; }

        String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
        String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
        loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
        // Init the text field in case it's read without editing the text before
        mJsObject.text = text;
    }

    public String getText() {
        return mJsObject.text;
    }
}

这里是作为 Gist 的组件。

注意:我不需要原始解决方案中的高度变化回调,因此此处缺少该回调,但如果需要,您可以轻松添加它。

May I suggest a somewhat hacky but still genius solution! I got the idea from this article and adapted it for Android. Basically you use a WebView and insert the HTML you want to show and edit in an editable div tag. This way when the user taps the WebView the keyboard appears and allows editing. They you just add some JavaScript to get back the edited HTML and voila!

Here is the code:

public class HtmlTextEditor extends WebView {

    class JsObject {
        // This field always keeps the latest edited text
        public String text;
        @JavascriptInterface
        public void textDidChange(String newText) {
            text = newText.replace("\n", "");
        }
    }

    private JsObject mJsObject;

    public HtmlTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        getSettings().setJavaScriptEnabled(true);
        mJsObject = new JsObject();
        addJavascriptInterface(mJsObject, "injectedObject");
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadUrl(
                        "javascript:(function() { " +
                            "    var editor = document.getElementById(\"editor\");" +
                            "    editor.addEventListener(\"input\", function() {" +
                            "        injectedObject.textDidChange(editor.innerHTML);" +
                            "    }, false)" +
                            "})()");
            }
        });
    }

    public void setText(String text) {
        if (text == null) { text = ""; }

        String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
        String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
        loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
        // Init the text field in case it's read without editing the text before
        mJsObject.text = text;
    }

    public String getText() {
        return mJsObject.text;
    }
}

And here is the component as a Gist.

Note: I didn't need the height change callback from the original solution so that's missing here but you can easily add it if needed.

噩梦成真你也成魔 2024-08-26 07:27:29

您可以使用 HtmlDsl< 为 Android TextView 构建有效的 HTML /a> Github 上的库:https://github.com/jaredrummler/HtmlDsl

该库提供语法糖,通过仅支持由 Android 呈现的元素和属性,使代码更易于理解且不易出错。

创建一些 HTML 的示例:

textView.setHtml {
    h3("Android Versions:")
    ul {
        li {
            a(href = "https://developer.android.com/about/versions/12/get") {
                +"Android 12 Beta"
            }
        }
        li("Android 11")
        li("Android 10")
        li("Pie")
        li("Oreo")
        li("Nougat")
        li("Marshmallow")
        li("Lollipop")
        // ...
    }

    small {
        sub {
            +"by "
            a {
                href = "https://github.com/jaredrummler"
                text = "Jared Rummler"
            }
        }
    }
}

Android TextView 支持的 HTML 元素:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
<ul>
<li>

You can build valid HTML for Android TextView using the HtmlDsl library on Github: https://github.com/jaredrummler/HtmlDsl.

The library provides syntactic sugar to make the code more understandable and less error-prone by only supporting elements and attributes that are rendered by Android.

Example creating some HTML:

textView.setHtml {
    h3("Android Versions:")
    ul {
        li {
            a(href = "https://developer.android.com/about/versions/12/get") {
                +"Android 12 Beta"
            }
        }
        li("Android 11")
        li("Android 10")
        li("Pie")
        li("Oreo")
        li("Nougat")
        li("Marshmallow")
        li("Lollipop")
        // ...
    }

    small {
        sub {
            +"by "
            a {
                href = "https://github.com/jaredrummler"
                text = "Jared Rummler"
            }
        }
    }
}

Supported HTML elements for Android TextView:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
<ul>
<li>
终止放荡 2024-08-26 07:27:29

使用 BindingAdapter:

@BindingAdapter("renderHtml")
fun bindRenderHtml(view: TextView, description: String?) {
if (description != null) {
    view.text = HtmlCompat.fromHtml(description, FROM_HTML_MODE_COMPACT)
    view.movementMethod = LinkMovementMethod.getInstance()
} else {
    view.text = ""
}

}

用法:

  <TextView
        android:id="@+id/content_text_view"
        app:renderHtml="@{show.description}"
        ...

Using BindingAdapter:

@BindingAdapter("renderHtml")
fun bindRenderHtml(view: TextView, description: String?) {
if (description != null) {
    view.text = HtmlCompat.fromHtml(description, FROM_HTML_MODE_COMPACT)
    view.movementMethod = LinkMovementMethod.getInstance()
} else {
    view.text = ""
}

}

usage:

  <TextView
        android:id="@+id/content_text_view"
        app:renderHtml="@{show.description}"
        ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文