Android 显示 html 文本的最佳方式 [英] Android best way to display html text
问题描述
我有带有 html 标签
、links
、image links
的字符串,那么显示此字符串的最佳方式是什么?我知道人们为此使用 Webview
,但也许有一种方法可以在 textview 中做到这一点而无需投入太多工作?因为 WebView
会带来不同的问题,例如,如果您想更改文本颜色,则需要为该字符串添加额外的样式.我对如何使链接可点击并在同一文本视图中显示图像感兴趣.
I have string with html tags
, links
, image links
so what is the best way to display this string? I know that people using Webview
for that but maybe there is a way to do it in textview without putting too much work? Because with WebView
comes different problems for example if you want to change text color you need to add extra style to that string. I'm interested in ways to make links clickable and displaying Images in the same textview.
推荐答案
尝试使用这个
:-
Try using this
:-
Html.fromHtml("your html code");
示例
:-
Example
:-
txtvw.setText(Html.fromHtml("<p align=right> <b> "
+ "Hi!" + " <br/> <font size=6>"
+ " How are you "+"</font> <br/>"
+ "I am fine" + " </b> </p>"));
输出
:-
Output
:-
嗨
你好吗
我很好
**带有图片和超链接的完整代码**
:-
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
public class MainActivity extends Activity {
String htmlString = "<img src='ic_launcher'><i>Welcome to<i> <b><a href='https://stackoverflow.com/'>Stack Overflow</a></b>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView htmlTextView = new TextView(this);
setContentView(htmlTextView);
htmlTextView.setText(Html.fromHtml(htmlString, new Html.ImageGetter(){
@Override
public Drawable getDrawable(String source) {
Drawable drawable;
int dourceId =
getApplicationContext()
.getResources()
.getIdentifier(source, "drawable", getPackageName());
drawable =
getApplicationContext()
.getResources()
.getDrawable(dourceId);
drawable.setBounds(
0,
0,
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
return drawable;
}
}, null));
htmlTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
支持所有API使用此功能
:-
To support all API use this function
:-
@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
}
else {
return Html.fromHtml(html);
}
}
这篇关于Android 显示 html 文本的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!