Android展示Html富文本
2022-04-15 本文已影响0人
SeekLife0
1、展示富文本并可展示图片,点击图片可以进行预览。
<TextView
android:id="@+id/html_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
/>
htmlTv = findViewById(R.id.html_tv);
htmlTv.setMovementMethod(LinkMovementMethod.getInstance());
HtmlText.from(data.remarks).setImageLoader(new HtmlImageLoader() {
@Override
public void loadImage(String s, Callback callback) {
Glide.with(PreferDetailNewActivity.this)
.asBitmap()
.load(s)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
callback.onLoadComplete(resource);
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
callback.onLoadFailed();
}
});
}
@Override
public Drawable getDefaultDrawable() {
return (Drawable) ContextCompat.getDrawable(PreferDetailNewActivity.this, R.drawable.image_placeholder_loading);
}
@Override
public Drawable getErrorDrawable() {
return (Drawable) ContextCompat.getDrawable(PreferDetailNewActivity.this, R.drawable.image_placeholder_fail);
}
@Override
public int getMaxWidth() {
return htmlTv.getWidth();
}
@Override
public boolean fitWidth() {
return false;
}
}).setOnTagClickListener(new OnTagClickListener() {
@Override
public void onImageClick(Context context, List<String> list, int i) {
if (list != null) {
jup(i, list);
}
Log.e("详情图片点击调试", "已点击");
}
@Override
public void onLinkClick(Context context, String s) {
}
}).into(htmlTv);
private void jup(int position, List<String> list) {
PictureConfig.Builder builder = new PictureConfig.Builder();
PictureConfig picture = builder.setListData((ArrayList<String>) list)
.setPosition(position)
.setDownloadPath("PIC")
.needDownload(true) //是否支持下载
.setPlacrHolder(R.drawable.image_placeholder_loading) //占位符
.build();
ImagePagerActivity.startActivity(this, picture);
}
2、可以展示图片,以及大部分的html标签,但是图片不能预览
引入依赖:https://github.com/SufficientlySecure/html-textview
implementation 'org.sufficientlysecure:html-textview:4.0'
<org.sufficientlysecure.htmltextview.HtmlTextView
android:id="@+id/tv_rich_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="20dp"
android:textColor="#7F7F7F"
/>
htmlTv = findViewById(R.id.tv_rich_text);
htmlTv.setHtml(entity.getTitle(), new HtmlHttpImageGetter(htmlTv));
3、出现富文本无法展示的问题,还可以使用WebView进行显示富文本
webView如果使用xml布局方式实现,会出现高度无法自适应的情况,所有改用代码实现。
参考:https://www.jianshu.com/p/3b892cacd1c5
使用:
wv = WebView(me)
wv.loadDataWithBaseURL(null, data.ruleWords, "text/html", "utf-8", null) //data.ruleWords是你的富文本
sllHtml.addView(wv) //添加到一个LinearLayout布局