我有html tags
,links
,image links
的字符串,那么显示此字符串的最佳方式是什么?我知道有人使用Webview
,但也许有一种方法可以在textview中进行,而不需要做太多的工作?因为WebView
会出现不同的问题,例如,如果要更改文本颜色,则需要为该字符串添加额外的样式。我对如何使链接可点击并在同一文本视图中显示图像感兴趣。
答案 0 :(得分:1)
<强> 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
强>: -
嗨
你好吗?
我很好
**Full Code With Image And Hyperlink**
: -
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());
}
}
<强> 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); } }