【问题标题】:java android - how to set html from resources to TextView?java android - 如何将html从资源设置为TextView?
【发布时间】:2013-08-27 14:38:48
【问题描述】:

是否有可能将 html 从 res/raw 加载到 TextView 中? 我知道我可以使用 WebView,但该死的透明度并不总是有效(不是在所有设备上)

【问题讨论】:

    标签: java android html textview


    【解决方案1】:

    您可以将您的 html 内容放在 string 资源中,并通过以下方式在您的 TextView 中使用它:

    textView.setText(Html.fromHtml(getResource().getString(R.string.my_html)));
    

    要在 strings.xml 文件中格式化您的 HTML,请使用该语法:

    <string name="my_html">
        <![CDATA[
        Your html content here
        ]]>
    </string>
    

    【讨论】:

      【解决方案2】:

      对于简单的 HTML 内容,您可以使用 .setText(Html.fromHtml("Hello world!"))。只需load html file to string from raw

      【讨论】:

        【解决方案3】:
        myTextView.setText(Html.fromHtml(readTxt()));     
        

        //此函数将返回您可以在文本视图中设置的字符串。并且该字符串具有 html 代码,因此请使用 Html.fromHtml

         private String readTxt() {
            InputStream inputStream = getResources().openRawResource(R.raw.My_html_file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int i;
            try {
                i = inputStream.read();
                while (i != -1) {
                    byteArrayOutputStream.write(i);
                    i = inputStream.read();
                }
                inputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return byteArrayOutputStream.toString();
          }
        

        【讨论】:

        • 非常感谢!结果让我震惊:) 它绝对不像 html 中的样子
        • 嗯,是的,我的问题已解决 - 无法让 textview 的 html 看起来像 webview 的 html - 文本格式不同
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-15
        • 1970-01-01
        • 2017-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多