解析展示文字图片混排的(不是真正的html格式)
2019-01-04 本文已影响10人
zhengLH
【需求】服务端 返回富文本形式(实则不是真正意义上的html文本)
图片.png【工具类】
/**
* @Author Lee
* @Time 2018/9/18
* @Theme
*/
public class HtmlTextView extends TextView {
public static final String TAG = "HtmlTextView";
public static final boolean DEBUG = false;
public HtmlTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public HtmlTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HtmlTextView(Context context) {
super(context);
}
/**
* @param is * @return
*/
static private String convertStreamToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
/**
* Parses String containing HTML to Android's Spannable format and displays * it in this TextView. * * @param html String containing HTML, for example: "<b>Hello world!</b>"
*/
public void setHtmlFromString(String html, boolean useLocalDrawables) {
Html.ImageGetter imgGetter = null;
if (useLocalDrawables) {
// imgGetter = new LocalImageGetter(getContext());
} else {
imgGetter = new UrlImageGetter(this, getContext());
}
// this uses Android's Html class for basic parsing, and HtmlTagHandler
setText(Html.fromHtml(html, imgGetter, new Html.TagHandler() {
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
}
}));
// make links work
setMovementMethod(LinkMovementMethod.getInstance());
setTextColor(getResources().getColor(R.color.shell_news_content));
}
}
【使用】
(1)在布局中:
<com.shuixin.mvpshell.widget.HtmlTextView
android:id="@+id/htv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/shell_font_black"
android:textSize="18sp"/>
(2) 在代码中:
mHtv.setHtmlFromString(“ ”,false);