HtmlTextView 是一个开源的 Android HTML 展示库,支持常用的HTML的标签,以及图片展示,其中 <a> 标签支持设置监听,而 <img /> 标签未实现,本文介绍如何快速设置图片点击监听。
开源库地址:https://github.com/SufficientlySecure/html-textview
一、在项目的模块中引入
implementation 'org.sufficientlysecure:html-textview:4.0'
二、在布局中使用控件
<org.sufficientlysecure.htmltextview.HtmlTextView
android:id="@+id/htmlTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@android:style/TextAppearance.Small"/>
三、展示内容
String html = "<p><img src=\"https://img.ivsky.com/img/tupian/pre/201903/24/richu_riluo-013.jpg\"/></p>";
HtmlTextView htmlTextView = findViewById(R.id.htmlTv);
htmlTextView.setHtml(html, new HtmlHttpImageGetter(htmlTextView));
由于是网络图片,别忘了添加对应的权限
<uses-permission android:name="android.permission.INTERNET"/>
效果如下
四、给图片添加点击监听
其实就是只要在 <img /> 加上 <a> 标签包裹,然后给 <a> 标签指定图片的下标,具体实现如下
/** 将图片列表拼接成HTML内容 */
public static String listToString(List<String> list) {
StringBuilder sb = new StringBuilder();
for (int idx = 0; idx < list.size(); idx++)
{
sb.append("<a href=\"")
.append(idx)
.append("\"><img src=\"")
.append(list.get(idx))
.append("\" /></a>");
sb.append("<p>");
}
return sb.toString();
}
设置监听
List<String> galleries = Arrays.asList(
"https://img.ivsky.com/img/tupian/pre/201903/24/richu_riluo-013.jpg",
"https://img.ivsky.com/img/tupian/pre/201903/24/richu_riluo-013.jpg",
"https://img.ivsky.com/img/tupian/pre/201903/24/richu_riluo-013.jpg"
);
final String html = listToString(galleries);
htmlTextView.setHtml(html, new HtmlHttpImageGetter(htmlTextView));
htmlTextView.setOnClickATagListener((widget, spannedText, href) -> {
Toast.makeText(getContext(), href, Toast.LENGTH_SHORT).show();
return true;
});
得到下标就可以找到对应的图片。