androidtextviewonclicklistenerspannedlinkmovementmethod

OnClickListener for TextView does not get called


I have a couple of text links in my Android applications which are either email addresses or web links. I use the following code snippet to set them up (example for a web link):

TextView textView = (TextView) findViewById(textViewId);
spannedText = Html.fromHtml("<a href=\"" + url + "\">" + titleText + "</a>");
textView.setText(spannedText, TextView.BufferType.SPANNABLE);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Handle click
    }
});

The TextView has no special attributes set such as android:linksClickable, android:clickable or android:focusable. Its style inherits from @android:style/TextAppearance.Small.

For some reason the OnClickListener never gets called.


Solution

  • remove this code

    textView.setMovementMethod(LinkMovementMethod.getInstance());
    

    and manually add the following a link

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Handle click
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
    
        }
    });