HtmlTextView 处理图片点击事件

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;
});

得到下标就可以找到对应的图片。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值