是否有可能通过textview显示纯html代码android
问题描述:
我试图用我的android应用程序上的TextView显示HTML字符串。 我很好奇,如何能够通过TextView使用内联样式显示HTML。 有一些原因,我们无法为此使用WebView。 GitHub上有任何知道它有效的存储库吗?是否有可能通过textview显示纯html代码android
感谢您的帮助。
只是为了您的关注,我们需要在API完美地运行15
答
您需要使用Html.fromHtml()使用HTML你textView
为文本
例如:
textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
答
我不记得我得到的来源,但我做了这种方式:
在xml文件HTML字符串:
<resources>
<string name="app_name">TestProject2</string>
<string name="html">
<![CDATA[
<h1>Main Title</h1>
<h2>A sub-title</h2>
<p>This is some html. Look, here\'s an <u>underline</u>.</p>
<p>Look, this is <em>emphasized.</em> And here\'s some <b>bold</b>.</p>
<p>This is a UL list:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<p>This is an OL list:
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ol>
]]>
</string>
</resources>
定义上的TextView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="top|fill_vertical">
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<!--
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/webView"
android:layout_below="@+id/helloWorld"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
-->
</LinearLayout>
而且在主要活动
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get our html content
String htmlAsString = getString(R.string.html); // used by WebView
Spanned htmlAsSpanned = Html.fromHtml(htmlAsString); // used by TextView
// set the html content on a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(htmlAsSpanned);
// WebView webView = (WebView) findViewById(R.id.webView);
// webView.loadDataWithBaseURL(null, htmlAsString, "text/html", "utf-8", null);
}
}
+0
不是一个选项。我们必须支持内联风格。 Like style =“font-size:20px; font-weight:600; color:#FF0000; text-align:center;” – Frank
您可以使用 “Html.fromHtml” 但TextView中只支持有限的标签https://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html。我们知道yu不能使用webview吗? –
这是我们PM的令人毛骨悚然的要求。 – Frank