143

我有一个 TextView,它呈现基本的 HTML,包含 2 个以上的链接。我需要捕获对链接的点击并打开链接——在我自己的内部 WebView 中(而不是在默认浏览器中。)

处理链接渲染的最常用方法似乎是这样的:

String str_links = "<a href='http://google.com'>Google</a><br /><a href='http://facebook.com'>Facebook</a>";
text_view.setLinksClickable(true);
text_view.setMovementMethod(LinkMovementMethod.getInstance());
text_view.setText( Html.fromHtml( str_links ) );

但是,这会导致链接在默认的内部 Web 浏览器中打开(显示“使用...完成操作”对话框)。

我尝试实现一个 onClickListener,它会在单击链接时正确触发,但我不知道如何确定单击了哪个链接...

text_view.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        // what now...?
    }

});

或者,我尝试创建一个自定义 LinkMovementMethod 类并实现 onTouchEvent ...

public boolean onTouchEvent(TextView widget, Spannable text, MotionEvent event) {
    String url = text.toString();
    // this doesn't work because the text is not necessarily a URL, or even a single link... 
    // eg, I don't know how to extract the clicked link from the greater paragraph of text
    return false;
}

想法?


示例解决方案

我想出了一个解决方案,它解析 HTML 字符串中的链接并使其可点击,然后让您响应 URL。

4

12 回答 12

257

根据另一个答案,这里有一个函数 setTextViewHTML(),它解析 HTML 字符串中的链接并使它们可点击,然后让您响应 URL。

protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span)
{
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            // Do something with span.getURL() to handle the link click...
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}

protected void setTextViewHTML(TextView text, String html)
{
    CharSequence sequence = Html.fromHtml(html);
    SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
    URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);   
    for(URLSpan span : urls) {
        makeLinkClickable(strBuilder, span);
    }
    text.setText(strBuilder);
    text.setMovementMethod(LinkMovementMethod.getInstance());       
}
于 2013-11-14T22:22:32.023 回答
29

我在Kotlin中创建了一个简单的扩展函数,通过对 URLSpan 元素应用新的回调来捕获 TextView 中的 url 链接点击。

strings.xml(文本中的示例链接)

<string name="link_string">this is my link: <a href="https://www.google.com/">CLICK</a></string>

确保在调用“handleUrlClicks”之前将跨区文本设置为 TextView

textView.text = getString(R.string.link_string)

这是扩展功能:

/**
 * Searches for all URLSpans in current text replaces them with our own ClickableSpans
 * forwards clicks to provided function.
 */
fun TextView.handleUrlClicks(onClicked: ((String) -> Unit)? = null) {
    //create span builder and replaces current text with it
    text = SpannableStringBuilder.valueOf(text).apply {
        //search for all URL spans and replace all spans with our own clickable spans
        getSpans(0, length, URLSpan::class.java).forEach {
            //add new clickable span at the same position
            setSpan(
                object : ClickableSpan() {
                    override fun onClick(widget: View) {
                        onClicked?.invoke(it.url)
                    }
                },
                getSpanStart(it),
                getSpanEnd(it),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
            //remove old URLSpan
            removeSpan(it)
        }
    }
    //make sure movement method is set
    movementMethod = LinkMovementMethod.getInstance()
}

这就是我所说的:

textView.handleUrlClicks { url ->
    Timber.d("click on found span: $url")
}
于 2019-11-20T14:05:44.600 回答
23

您已完成以下操作:

text_view.setMovementMethod(LinkMovementMethod.getInstance());
text_view.setText( Html.fromHtml( str_links ) );

您是否尝试过如下所示的相反顺序?

text_view.setText( Html.fromHtml( str_links ) );
text_view.setMovementMethod(LinkMovementMethod.getInstance());

并且没有:

text_view.setLinksClickable(true);
于 2013-09-05T00:31:43.333 回答
22

这可以通过使用 Spannable String 来简单地解决。你真正想做的(业务需求)对我来说有点不清楚,所以下面的代码不会对你的情况给出确切的答案,但我敢肯定它会给你一些想法和您将能够根据以下代码解决您的问题。

正如您所做的那样,我还通过 HTTP 响应获取了一些数据,并且在我的案例“更多”中添加了一些额外的下划线文本,这个带下划线的文本将在点击事件时打开 Web 浏览器。希望这会对您有所帮助。

TextView decription = (TextView)convertView.findViewById(R.id.library_rss_expan_chaild_des_textView);
String dec=d.get_description()+"<a href='"+d.get_link()+"'><u>more</u></a>";
CharSequence sequence = Html.fromHtml(dec);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
UnderlineSpan[] underlines = strBuilder.getSpans(0, 10, UnderlineSpan.class);   
for(UnderlineSpan span : underlines) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan myActivityLauncher = new ClickableSpan() {
        public void onClick(View view) {
            Log.e(TAG, "on click");
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(d.get_link()));
            mContext.startActivity(intent);         
        }
    };
    strBuilder.setSpan(myActivityLauncher, start, end, flags);
}
decription.setText(strBuilder);
decription.setLinksClickable(true);
decription.setMovementMethod(LinkMovementMethod.getInstance());
于 2012-09-14T05:34:00.747 回答
18

我也遇到过同样的问题,但是文本很多,链接和电子邮件很少。我认为使用“autoLink”是一种更简单、更清洁的方法:

  text_view.setText( Html.fromHtml( str_links ) );
  text_view.setLinksClickable(true);
  text_view.setAutoLinkMask(Linkify.ALL); //to open links

您可以设置 Linkify.EMAIL_ADDRESSES 或 Linkify.WEB_URLS 如果您只想使用其中一个或从 XML 布局设置

  android:linksClickable="true"
  android:autoLink="web|email"

可用选项包括:无、网络、电子邮件、电话、地图、全部

于 2012-10-09T12:02:44.523 回答
12

解决方案

我已经实现了一个小类,借助它您可以处理对 TextView 本身的长时间点击以及对 TextView 中链接的点击。

布局

TextView android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="all"/>

TextViewClickMovement.java

import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;

public class TextViewClickMovement extends LinkMovementMethod {

    private final String TAG = TextViewClickMovement.class.getSimpleName();

    private final OnTextViewClickMovementListener mListener;
    private final GestureDetector                 mGestureDetector;
    private TextView                              mWidget;
    private Spannable                             mBuffer;

    public enum LinkType {

        /** Indicates that phone link was clicked */
        PHONE,

        /** Identifies that URL was clicked */
        WEB_URL,

        /** Identifies that Email Address was clicked */
        EMAIL_ADDRESS,

        /** Indicates that none of above mentioned were clicked */
        NONE
    }

    /**
     * Interface used to handle Long clicks on the {@link TextView} and taps
     * on the phone, web, mail links inside of {@link TextView}.
     */
    public interface OnTextViewClickMovementListener {

        /**
         * This method will be invoked when user press and hold
         * finger on the {@link TextView}
         *
         * @param linkText Text which contains link on which user presses.
         * @param linkType Type of the link can be one of {@link LinkType} enumeration
         */
        void onLinkClicked(final String linkText, final LinkType linkType);

        /**
         *
         * @param text Whole text of {@link TextView}
         */
        void onLongClick(final String text);
    }


    public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
        mListener        = listener;
        mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
    }

    @Override
    public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {

        mWidget = widget;
        mBuffer = buffer;
        mGestureDetector.onTouchEvent(event);

        return false;
    }

    /**
     * Detects various gestures and events.
     * Notify users when a particular motion event has occurred.
     */
    class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent event) {
            // Notified when a tap occurs.
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // Notified when a long press occurs.
            final String text = mBuffer.toString();

            if (mListener != null) {
                Log.d(TAG, "----> Long Click Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                                  "Text: " + text + "\n<----");

                mListener.onLongClick(text);
            }
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent event) {
            // Notified when tap occurs.
            final String linkText = getLinkText(mWidget, mBuffer, event);

            LinkType linkType = LinkType.NONE;

            if (Patterns.PHONE.matcher(linkText).matches()) {
                linkType = LinkType.PHONE;
            }
            else if (Patterns.WEB_URL.matcher(linkText).matches()) {
                linkType = LinkType.WEB_URL;
            }
            else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
                linkType = LinkType.EMAIL_ADDRESS;
            }

            if (mListener != null) {
                Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                                  "Link Text: " + linkText + "\n" +
                                  "Link Type: " + linkType + "\n<----");

                mListener.onLinkClicked(linkText, linkType);
            }

            return false;
        }

        private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                return buffer.subSequence(buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0])).toString();
            }

            return "";
        }
    }
}

用法

String str_links = "<a href='http://google.com'>Google</a><br /><a href='http://facebook.com'>Facebook</a>";
text_view.setText( Html.fromHtml( str_links ) );
text_view.setMovementMethod(new TextViewClickMovement(this, context));

链接

希望这有帮助!你可以在这里找到代码。

于 2016-05-13T08:39:13.193 回答
8

一种更清洁、更好的解决方案,使用本机的Linkify 库

例子:

Linkify.addLinks(mTextView, Linkify.ALL);
于 2015-12-10T09:01:32.063 回答
7

如果您使用的是 Kotlin,我为这种情况编写了一个简单的扩展:

/**
 * Enables click support for a TextView from a [fullText] String, which one containing one or multiple URLs.
 * The [callback] will be called when a click is triggered.
 */
fun TextView.setTextWithLinkSupport(
    fullText: String,
    callback: (String) -> Unit
) {
    val spannable = SpannableString(fullText)
    val matcher = Patterns.WEB_URL.matcher(spannable)
    while (matcher.find()) {
        val url = spannable.toString().substring(matcher.start(), matcher.end())
        val urlSpan = object : URLSpan(fullText) {
            override fun onClick(widget: View) {
                callback(url)
            }
        }
        spannable.setSpan(urlSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    text = spannable
    movementMethod = LinkMovementMethod.getInstance() // Make link clickable
}

用法:

yourTextView.setTextWithLinkSupport("click on me: https://www.google.fr") {
   Log.e("URL is $it")
}
于 2019-10-22T13:55:47.950 回答
1

另一种更简单的方法(对于像我这样的懒惰开发人员;)

abstract class LinkAwareActivity : AppCompatActivity() {

    override fun startActivity(intent: Intent?) {
        if(Intent.ACTION_VIEW.equals(intent?.action) && onViewLink(intent?.data.toString(), intent)){
            return
        }

        super.startActivity(intent)
    }

    // return true to consume the link (meaning to NOT call super.startActivity(intent))
    abstract fun onViewLink(url: String?, intent: Intent?): Boolean 
}

如果需要,您还可以检查意图的方案/模仿类型

于 2020-06-09T17:38:33.587 回答
0

我只使用 textView,并为 url 设置跨度并处理点击。

我在这里找到了非常优雅的解决方案,没有链接 - 据我知道我想链接字符串的哪一部分

在我的 android 应用程序中处理 textview 链接点击

在科特林:

fun linkify(view: TextView, url: String, context: Context) {

    val text = view.text
    val string = text.toString()
    val span = ClickSpan(object : ClickSpan.OnClickListener {
        override fun onClick() {
            // handle your click
        }
    })

    val start = string.indexOf(url)
    val end = start + url.length
    if (start == -1) return

    if (text is Spannable) {
        text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        text.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.orange)),
                start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    } else {
        val s = SpannableString.valueOf(text)
        s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        s.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.orange)),
                start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        view.text = s
    }

    val m = view.movementMethod
    if (m == null || m !is LinkMovementMethod) {
        view.movementMethod = LinkMovementMethod.getInstance()
    }
}

class ClickSpan(private val mListener: OnClickListener) : ClickableSpan() {

    override fun onClick(widget: View) {
        mListener.onClick()
    }

    interface OnClickListener {
        fun onClick()
    }
}

和用法:linkify(yourTextView, urlString, context)

于 2017-08-02T11:24:08.540 回答
0

您可以使用名为Better-Link-Movement-Method的简单库更巧妙地完成此操作。

    TextView mTvUrl=findViewById(R.id.my_tv_url);
    mTvUrl.setMovementMethod(BetterLinkMovementMethod.newInstance().setOnLinkClickListener((textView, url) -> {
              
                    if (Patterns.WEB_URL.matcher(url).matches()) {
                        //An web url is detected 
                        return true;
                    }
                    else if(Patterns.PHONE.matcher(url).matches()){
                        //A phone number is detected 
                        return true;
                    }
                    else if(Patterns.EMAIL_ADDRESS.matcher(url).matches()){
                        //An email address is detected 
                        return true;
                    }
    
                return false;
            }));
于 2021-01-06T15:48:50.693 回答
0

这个页面解决了我的问题,但我必须自己想办法。我正在使用 android 字符串资源来设置 TextView 的文本,显然,它们返回了一个在文本之间有链接的CharSequence 。

这些是资源:

<string name="license_agreement">By registering, you agree with our <b><ahref="www.privacy-options.com">Privacy Policy</a></b> and <b><a href="www.terms-and-conditions.com">Terms and Conditions</a></b></string>

<string name="sign_now">Already have an account? <b><a href="@login_page">Login</a></b></string>

我对建议的代码之一进行了更改。编码:

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ...

        // Make Licence agreement statements and login text clickable links
        setLinkOnText(binding.txtLcAgree);
        setLinkOnText(binding.signNow);

    }

    private void detectLinkClick(SpannableStringBuilder strBuilder, final URLSpan span) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            // Do something with links retrieved from span.getURL(), to handle link click...
            String clickedUrl = span.getURL();
            switch (clickedUrl) {
                case "@login_page":
                    startActivity(new Intent(RegistrationActivity.this, LoginActivity.class));
                    break;
                case "http://www.privacy-options.com":
                    Uri link1 = Uri.parse("http://www.privacy-options.com");
                    startActivity(new Intent(Intent.ACTION_VIEW, link1));
                    break;
                case "http://www.terms-and-conditions.com":
                    Uri link2 = Uri.parse("http://www.terms-and-conditions.com");
                    startActivity(new Intent(Intent.ACTION_VIEW, link2));
                    break;
                default:
                    Log.w(getClass().getSimpleName(), "No action for this");

            }
        }
    };

    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}

    protected void setLinkOnText(TextView text) {
        CharSequence sequence = text.getText();
        SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
        URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
        for (URLSpan span : urls) {
            detectLinkClick(strBuilder, span);
        }
        text.setText(strBuilder);
        text.setMovementMethod(LinkMovementMethod.getInstance());
    }

从中检索的span.getUrl()链接是我在字符串资源中设置的初始链接。由于 TextView 中的文本已经是链接格式,我只是简单地在SpannableStringBuilder中使用了该文本。

于 2021-05-20T07:32:52.037 回答